So far I have the following code:
import java.util.Scanner;
public class HallLanceMemoryCalculator {
private double currentValue;
public static int displayMenu(){
Scanner input=new Scanner(System.in);
int choice=0;
while(choice<1||choice>5){
System.out.println("1.Add");
System.out.println("2.Subtract");
System.out.println("3.Multiply");
System.out.println("4.Divide");
System.out.println("5.Clear");
System.out.println("What would you like to do?");
choice=input.nextInt();
}
return choice;
}
public static double getOperand(String prompt){
Scanner input=new Scanner(System.in);
System.out.println("What is the second number?");
double secondNumber=input.nextDouble();
return secondNumber;
}
public double getCurrentValue(){
return currentValue;
}
public void add(double operand2){
currentValue+=operand2;
}
public void subtract(double operand2){
currentValue-=operand2;
}
public void multiply(double operand2){
currentValue*=operand2;
}
public void divide(double operand2){
currentValue/=operand2;
}
public void clear(){
currentValue=0;
}
public static void main(String[] args) {
double value=getCurrentValue();
}
}
When I try to set double value=getCurrentValue(); at the end, I get an error message "Cannot make a static reference to the non-static method." It says the fix is to make the getCurrentValue() method static as well, but I was told not to make that field static by my professor. Is there a simple solution to this that I am just missing?
A static method belongs to the class, a non-static method belongs to an instance of the class.
When you call getCurrentValue() from main, you get an error because main isn't associated with any instance.
You need to create an instance of the class:
HallLanceMemoryCalculator me = new HallLanceMemoryCalculator();
Then you can call the instance's getCurrentValue():
double value = me.getCurrentValue();
Static means there is one for an entire class, whereas if it is non-static there is one for each instance of a class (object). In order to reference a non-static method from a static context, you need to first create an object for that method to be a part of. So, in your main method (the static context), you need to create a new HallLanceMemoryCalculator object. Once you have the object, you can use the object's methods.
The reason your professor does not want it to be static, is so that you have the ability to have multiple HallLanceMemoryCalculator instances, that each keep track of their own value.
Note, I'm not including any code, because I'm sure your professor would want you to figure out that part on your own.
The Method getCurrentValue() is defined as an ordniary (non-static) method of the class. In order to execute it, you need an instance of HallLanceMemoryCalculator.
So try to instantiate HallLanceMemoryCalculator first:
HallLanceMemoryCalculator calc = new HallLanceMemoryCalculator();
double value = calc.getValue();
In order to make some sense, the example should have a constructor for storing the initial value. E.g.
public HallLanceMemoryCalculator(double initial) {
this.currentValue = initial;
}
In doing so, you can use the following main code:
HallLanceMemoryCalculator calc = new HallLanceMemoryCalculator(10);
int choice = displayMenu();
// some code to get the second operand (you don't need the string as param)
double operand = getOperand("");
// some switch statement to handle the choice
...
double result = calc.getCurrentValue();
Create an instance of your HallLanceMemoryCalculator then call getCurrentValue() or make getCurrentValue() static.
you should use an instance of the class and not the class if you want to call your getter function without setting the attribute static.
Related
I have a simple question that I just can't figure out a good answer for. Why does the following Java program display 20? I would prefer a detailed response if possible please.
class Something{
public int x;
public Something(){
x=aMethod();
}
public static int aMethod(){
return 20;
}
}
class SomethingElse extends Something{
public static int aMethod(){
return 40;
}
public static void main(String[] args){
SomethingElse m;
m=new SomethingElse();
System.out.println(m.x);
}
}
Because polymorphism only applies to instance methods.
The static method aMethod invoked here
public Something(){
x=aMethod();
}
refers to the aMethod declared in Something.
The inheritance for static methods works differently then non-static one. In particular the superclass static method are NOT overridden by the subclass. The result of the static method call depends on the object class it is invoke on. Variable x is created during the Something object creation, and therefore that class (Something) static method is called to determine its value.
Consider following code:
public static void main(String[] args){
SomethingElse se = new SomethingElse();
Something sg = se;
System.out.println(se.aMethod());
System.out.println(sg.aMethod());
}
It will correctly print the 40, 20 as each object class invokes its own static method. Java documentation describes this behavior in the hiding static methods part.
Because int x is declared in the class Something. When you make the SomethingElse object, you first make a Something object (which has to set x, and it uses the aMethod() from Something instead of SomethingElse (Because you are creating a Something)). This is because aMethod() is static, and polymorphism doesn't work for static methods. Then, when you print the x from m, you print 20 since you never changed the value of x.
See the code snippets below:
Code 1
public class A {
static int add(int i, int j) {
return(i + j);
}
}
public class B extends A {
public static void main(String args[]) {
short s = 9;
System.out.println(add(s, 6));
}
}
Code 2
public class A {
int add(int i, int j) {
return(i + j);
}
}
public class B extends A {
public static void main(String args[]) {
A a = new A();
short s = 9;
System.out.println(a.add(s, 6));
}
}
What is the difference between these code snippets? Both output 15 as an answer.
A static method belongs to the class itself and a non-static (aka instance) method belongs to each object that is generated from that class. If your method does something that doesn't depend on the individual characteristics of its class, make it static (it will make the program's footprint smaller). Otherwise, it should be non-static.
Example:
class Foo {
int i;
public Foo(int i) {
this.i = i;
}
public static String method1() {
return "An example string that doesn't depend on i (an instance variable)";
}
public int method2() {
return this.i + 1; // Depends on i
}
}
You can call static methods like this: Foo.method1(). If you try that with method2, it will fail. But this will work: Foo bar = new Foo(1); bar.method2();
Static methods are useful if you have only one instance (situation, circumstance) where you're going to use the method, and you don't need multiple copies (objects). For example, if you're writing a method that logs onto one and only one web site, downloads the weather data, and then returns the values, you could write it as static because you can hard code all the necessary data within the method and you're not going to have multiple instances or copies. You can then access the method statically using one of the following:
MyClass.myMethod();
this.myMethod();
myMethod();
Non-static methods are used if you're going to use your method to create multiple copies. For example, if you want to download the weather data from Boston, Miami, and Los Angeles, and if you can do so from within your method without having to individually customize the code for each separate location, you then access the method non-statically:
MyClass boston = new MyClassConstructor();
boston.myMethod("bostonURL");
MyClass miami = new MyClassConstructor();
miami.myMethod("miamiURL");
MyClass losAngeles = new MyClassConstructor();
losAngeles.myMethod("losAngelesURL");
In the above example, Java creates three separate objects and memory locations from the same method that you can individually access with the "boston", "miami", or "losAngeles" reference. You can't access any of the above statically, because MyClass.myMethod(); is a generic reference to the method, not to the individual objects that the non-static reference created.
If you run into a situation where the way you access each location, or the way the data is returned, is sufficiently different that you can't write a "one size fits all" method without jumping through a lot of hoops, you can better accomplish your goal by writing three separate static methods, one for each location.
Generally
static: no need to create object we can directly call using
ClassName.methodname()
Non Static: we need to create a object like
ClassName obj=new ClassName()
obj.methodname();
A static method belongs to the class
and a non-static method belongs to an
object of a class. That is, a
non-static method can only be called
on an object of a class that it
belongs to. A static method can
however be called both on the class as
well as an object of the class. A
static method can access only static
members. A non-static method can
access both static and non-static
members because at the time when the
static method is called, the class
might not be instantiated (if it is
called on the class itself). In the
other case, a non-static method can
only be called when the class has
already been instantiated. A static
method is shared by all instances of
the class. These are some of the basic
differences. I would also like to
point out an often ignored difference
in this context. Whenever a method is
called in C++/Java/C#, an implicit
argument (the 'this' reference) is
passed along with/without the other
parameters. In case of a static method
call, the 'this' reference is not
passed as static methods belong to a
class and hence do not have the 'this'
reference.
Reference:Static Vs Non-Static methods
Well, more technically speaking, the difference between a static method and a virtual method is the way the are linked.
A traditional "static" method like in most non OO languages gets linked/wired "statically" to its implementation at compile time. That is, if you call method Y() in program A, and link your program A with library X that implements Y(), the address of X.Y() is hardcoded to A, and you can not change that.
In OO languages like JAVA, "virtual" methods are resolved "late", at run-time, and you need to provide an instance of a class. So in, program A, to call virtual method Y(), you need to provide an instance, B.Y() for example. At runtime, every time A calls B.Y() the implementation called will depend on the instance used, so B.Y() , C.Y() etc... could all potential provide different implementations of Y() at runtime.
Why will you ever need that? Because that way you can decouple your code from the dependencies. For example, say program A is doing "draw()". With a static language, thats it, but with OO you will do B.draw() and the actual drawing will depend on the type of object B, which, at runtime, can change to square a circle etc. That way your code can draw multiple things with no need to change, even if new types of B are provided AFTER the code was written. Nifty -
A static method belongs to the class and a non-static method belongs to an object of a class.
I am giving one example how it creates difference between outputs.
public class DifferenceBetweenStaticAndNonStatic {
static int count = 0;
private int count1 = 0;
public DifferenceBetweenStaticAndNonStatic(){
count1 = count1+1;
}
public int getCount1() {
return count1;
}
public void setCount1(int count1) {
this.count1 = count1;
}
public static int countStaticPosition() {
count = count+1;
return count;
/*
* one can not use non static variables in static method.so if we will
* return count1 it will give compilation error. return count1;
*/
}
}
public class StaticNonStaticCheck {
public static void main(String[] args){
for(int i=0;i<4;i++) {
DifferenceBetweenStaticAndNonStatic p =new DifferenceBetweenStaticAndNonStatic();
System.out.println("static count position is " +DifferenceBetweenStaticAndNonStatic.count);
System.out.println("static count position is " +p.getCount1());
System.out.println("static count position is " +DifferenceBetweenStaticAndNonStatic.countStaticPosition());
System.out.println("next case: ");
System.out.println(" ");
}
}
}
Now output will be:::
static count position is 0
static count position is 1
static count position is 1
next case:
static count position is 1
static count position is 1
static count position is 2
next case:
static count position is 2
static count position is 1
static count position is 3
next case:
If your method is related to the object's characteristics, you should define it as non-static method. Otherwise, you can define your method as static, and you can use it independently from object.
Static method example
class StaticDemo
{
public static void copyArg(String str1, String str2)
{
str2 = str1;
System.out.println("First String arg is: "+str1);
System.out.println("Second String arg is: "+str2);
}
public static void main(String agrs[])
{
//StaticDemo.copyArg("XYZ", "ABC");
copyArg("XYZ", "ABC");
}
}
Output:
First String arg is: XYZ
Second String arg is: XYZ
As you can see in the above example that for calling static method, I didn’t even use an object. It can be directly called in a program or by using class name.
Non-static method example
class Test
{
public void display()
{
System.out.println("I'm non-static method");
}
public static void main(String agrs[])
{
Test obj=new Test();
obj.display();
}
}
Output:
I'm non-static method
A non-static method is always be called by using the object of class as shown in the above example.
Key Points:
How to call static methods: direct or using class name:
StaticDemo.copyArg(s1, s2);
or
copyArg(s1, s2);
How to call a non-static method: using object of the class:
Test obj = new Test();
Basic difference is non static members are declared with out using the keyword 'static'
All the static members (both variables and methods) are referred with the help of class name.
Hence the static members of class are also called as class reference members or class members..
In order to access the non static members of a class we should create reference variable .
reference variable store an object..
Simply put, from the point of view of the user, a static method either uses no variables at all or all of the variables it uses are local to the method or they are static fields. Defining a method as static gives a slight performance benefit.
Another scenario for Static method.
Yes, Static method is of the class not of the object. And when you don't want anyone to initialize the object of the class or you don't want more than one object, you need to use Private constructor and so the static method.
Here, we have private constructor and using static method we are creating a object.
Ex::
public class Demo {
private static Demo obj = null;
private Demo() {
}
public static Demo createObj() {
if(obj == null) {
obj = new Demo();
}
return obj;
}
}
Demo obj1 = Demo.createObj();
Here, Only 1 instance will be alive at a time.
- First we must know that the diff bet static and non static methods
is differ from static and non static variables :
- this code explain static method - non static method and what is the diff
public class MyClass {
static {
System.out.println("this is static routine ... ");
}
public static void foo(){
System.out.println("this is static method ");
}
public void blabla(){
System.out.println("this is non static method ");
}
public static void main(String[] args) {
/* ***************************************************************************
* 1- in static method you can implement the method inside its class like : *
* you don't have to make an object of this class to implement this method *
* MyClass.foo(); // this is correct *
* MyClass.blabla(); // this is not correct because any non static *
* method you must make an object from the class to access it like this : *
* MyClass m = new MyClass(); *
* m.blabla(); *
* ***************************************************************************/
// access static method without make an object
MyClass.foo();
MyClass m = new MyClass();
// access non static method via make object
m.blabla();
/*
access static method make a warning but the code run ok
because you don't have to make an object from MyClass
you can easily call it MyClass.foo();
*/
m.foo();
}
}
/* output of the code */
/*
this is static routine ...
this is static method
this is non static method
this is static method
*/
- this code explain static method - non static Variables and what is the diff
public class Myclass2 {
// you can declare static variable here :
// or you can write int callCount = 0;
// make the same thing
//static int callCount = 0; = int callCount = 0;
static int callCount = 0;
public void method() {
/*********************************************************************
Can i declare a static variable inside static member function in Java?
- no you can't
static int callCount = 0; // error
***********************************************************************/
/* static variable */
callCount++;
System.out.println("Calls in method (1) : " + callCount);
}
public void method2() {
int callCount2 = 0 ;
/* non static variable */
callCount2++;
System.out.println("Calls in method (2) : " + callCount2);
}
public static void main(String[] args) {
Myclass2 m = new Myclass2();
/* method (1) calls */
m.method();
m.method();
m.method();
/* method (2) calls */
m.method2();
m.method2();
m.method2();
}
}
// output
// Calls in method (1) : 1
// Calls in method (1) : 2
// Calls in method (1) : 3
// Calls in method (2) : 1
// Calls in method (2) : 1
// Calls in method (2) : 1
Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier.
i.e. class human - number of heads (1) is static, same for all humans, however human - haircolor is variable for each human.
Notice that static vars can also be used to share information across all instances
public class MainForm {
String varpass = "This is a string that has to be passed.";
public String t1(){
String text = "This is a non-static method being called.";
return text;
}
public static String t2(){
String text = "This is a static method being called.";
return text;
}
public void t3(){
System.out.println("This is a non-static void method and cannot return.");
}
public static void t4(){
System.out.println("This is a static void method and cannot return.");
}
public void place1 (){
//=======================================Method calls from another class========================================
//Calls from another class. It is non-static and thus requires it to be instantiated. EG. class var = new class();
Methods call = new Methods();
System.out.println(call.t1());
//Calls from another class. It is non-static void and thus requires it to be instantiated and be called straight.
call.t3();
//Calls from another class. It is static and thus does not require it to be instantiated. EG. class var = new class();
System.out.println(Methods.t2());
//Calls from another class. It is static void and thus does not require it to be instantiated.
Methods.t4();
//Trying to call a variable that was sent.
Methods.getvar(varpass);
call.getvar(varpass);
//=======================================Method calls from current class========================================
MainForm mcall = new MainForm();
//Calls from within the same class. It is static and thus does not require it to be instantiated. EG. class var = new class();
System.out.println(mcall.t1());
mcall.t3();
System.out.println(t2());
t4();
}
public static void main(String[] args) {
MainForm place = new MainForm();
place.place1();
}
}
public class Methods {
String var1 = "This is a public String variable";
String getVar = "Initial";
public String t1(){
String text = "This is a non-static method being called.";
return text;
}
public static String t2(){
String text = "This is a static method being called.";
return text;
}
public void t3(){
System.out.println("This is a non-static void method and cannot return.");
}
public static void t4(){
System.out.println("This is a static void method and cannot return.");
}
public void getvar(String varsent){
String msg = "getver() Variables are varsent("+varsent+"), getVar("+getVar+"), getVar(";
getVar = varsent;
msg = msg + getVar+")";
System.out.println(msg);
}
}
Here is the errors below
Methods.getvar(varpass);
call.getvar(varpass);
top one is giving non-static cannot be referenced from a static context
bottom one is saying cannot resolve method 'println(void)'
You can tell im using this as practice to call methods.
Here im trying to pass a variable varpass that contains a string. I want it pass that variable to getvar in Methods. in that getvar it takes a variable in Methods displays it before altering it then again after alter.
Im trying to understand how this works. Any insight would be appreciated.
This line
Methods.getvar(varpass);
is a static call. You try to call the static Method getvar from your Methods class. This method however is not static and therefor requires an instance of Method.
This line
call.getvar(varpass);
works fine. It in fact is the solution to the first line, where you reffere a non-static method from a static context
You cannot refer to a non-static variable/field from a static method, because a non-static field may vary between instances of a class. To solve it, make varpass static:
static String varpass = "This is a string that has to be passed.";
The second error results from the definition of getvar:
public void getvar(String varsent);
Since it does not return anything, it cannot be used in a System.out.println() as there is no definition of println accepting void (It doesn't know what to print).
Also, Methods.getvar(varpass) should be Methods.getvar(MainForm.varpass), because there is no local variable with that name.
public class CodingBat {
public static void main(String[] args) {
System.out.println(sumDouble(5,5));
}
public int sumDouble(int a, int b) {
if( a ==b) {
return 2*a + 2* b;
} else{
return a + b;
}
}
}
So I made this code, and I'm really confused why it doesn't work unless I write static between the public int sumDouble, because I was practicing on codingBat, and to answer the question they did not involve static, but then how do they test code. Do they use the main? I mean you have to to get the code running right?
So to my knowledge, static means that every object of this class will all contain the same value.But I don't see the relevance of this error.
"Cannot make a static reference to the non-static method"
Thank you for your help :D
and I'm really confused why it doesn't work unless I write static
between the public int sumDouble,
Yes, static is required
Since the main method is static and the sumDouble() method is not, you can't call the method without creating object of class. You cannot refer non-static members from a static method.
Either make method static or create object as below and then access method.
CodingBat obj = new CodingBat();
System.out.println(obj.sumDouble(5,5));
Refer here for more
Either you call it through a static context, meaning like you do (or, from another class, by: ClassName.methodName(); )
Or, you have to call it as an instance method, which it is, if you don't declare it static.Then, however, you'll need an instance to call it through:
public static void main(String[] args){
CodingBat cB = new CodingBat();
System.out.println(cB.sumDouble(5,5));
}
You need to create an object in order to use this method
public class CodingBat {
public static void main(String[] args){
CodingBat obj = new CodingBat();
System.out.println(obj.sumDouble(5,5));
}
public int sumDouble(int a, int b) {
if( a ==b){
return 2*a + 2* b;}
else{
return a + b;}
}
}
Im doing a question that requires you to make a class customers which will later on be added into an array list in the method of another class. However I am getting an error on the line i marked ERROR, that says:
"No enclosing instance of type Question3 is accessible. Must qualify the allocation with an enclosing instance of type Question3 (e.g. x.new A() where x is an instance of Question3)." And I have no clue why.
public class Question3 {
static ArrayList<customers> a= new ArrayList<customers>();
private static Scanner kbd;
public static void main(String[] args)
{
String input="";
double price=1;
String name="";
while(price != 0)
{
System.out.println("Customer Name: ");
name= kbd.nextLine().trim();
System.out.println("Purchase Price: ");
price= Double.parseDouble(kbd.nextLine().trim());
addSale(name,price); //ERROR
}
}
public static void addSale(String name, double price)
{
customers c= new customers(name,price);
a.add(c);
}
public class customers
{
String name;
double price;
public customers(String name, double price)
{
this.name=name;
this.price=price;
}
}
}
You also have to initialize the kbd variable as:
kbd = new Scanner( System.in );
Please review your code using this suggestion and the others above.
A main method is static and thus has static context. No instance of Question3.class is required for a thread to enter that code block. Your class customers is defined inside of Question3. Because it is an inner class, it has implicit access to the fields and methods inside of the Question3 class, but it requires an instance of Question3 to be able to achieve that behavior. You need to move the code you have now in main(String args[]) into a constructor for the class Question3, and create an instance of Question3 in your main method like so :
public static void main(String args[]) {
Question3 myQuestion3 = new Question3();
}
Alternatively as mentioned by others, you could make your customers class static. This will solve the issue by effectively making customers a top level class, but you will lose the ability to implicitly access the fields and methods of its enclosing type, which is the Question3 class.
First off Great job so far. However, there are a couple of errors that I see in the code.
First you class should be a static class. You are trying to use static methods without a static class.
public static class Question3 {
static ArrayList<customers> a= new ArrayList<customers>();
private static Scanner kbd;
public static void main(String[] args)
{
Also, you need to create your scanner for the user to input an object.
private static Scanner kbd = new Scanner(System.In);
Do these and your code will work perfectly!
You should change the declaration your class customers to solve this issue.
Currently its a non-static inner class. You should change it to static inner class.
public static class customers
Non-static inner classes refers implicitly to the instance of the container class. Here you trying to create new instance of customer class in a static function, you don't have Question3 instance there.
Just change your inner class to a public static class:
public static class customers {
And the error disappears :)
There are two problems in your code.
First , you have to initialize scanner object by providing System.in parameter to it.
Second , while creating customer object you have to follow proper syntax.
Here is the working code:
public class Question3 {
static ArrayList<customers> a= new ArrayList<customers>();
private static Scanner kbd=new Scanner(System.in); // <---- Notice this
public static void main(String[] args)
{
String input="";
double price=1;
String name="";
while(price != 0)
{
System.out.println("Customer Name: ");
name= kbd.nextLine().trim();
System.out.println("Purchase Price: ");
price= Double.parseDouble(kbd.nextLine().trim());
addSale(name,price); //ERROR
}
System.out.println(a);
}
public static void addSale(String name, double price)
{
// customers c= new customers(name,price);
Question3.customers c = new Question3().new customers(name, price); // <---Notice this
a.add(c);
}
public class customers
{
String name;
double price;
public customers(String name, double price)
{
this.name=name;
this.price=price;
}
} }