Please help me I am facing bit problem in Java code.
I am not able to understand how to fix the error.
Please help.
public class A {
private int a = 100;
public void setA(int value) {
a = value;
}
public int getA() {
return a;
}
}
public class B extends A {
private int a = 222;
public static void main(String[] args) {
System.out.println("in main(): ");
a = 123;
System.out.println("a = "+super.a );
}
}
The error I get is:
int a in class Main must be static
First of all, you should tell us the error :).
It looks like you are trying to access a variable in a non-static context from a static context (main method is static).
You should do something like below:
public class B extends A {
public static void main(String[] args) {
B b = new B();
b.setA(123)
System.out.println("a = " + b.getA());
}
}
It doesn't make sense to declare another 'a' variable in the child class. If you want to access 'a' directly, you can declare the field in class A as protected.
First of all, just to be clear prior to going to the code, your 2 classes, given they are both public, must be in their own separate files.
Now let's go to your code. The error lies first in this statements inside your main method:
a = 123;
You are accessing B's instance variable a from a static context -this is one.
Second:
System.out.println("a = "+super.a );
A's instance variable a is never inherited by B because it has a private access modifier.
If you want to access A's a, you could create an instance of A, and use that to call the getA() method which returns the value of A's a
Cheers,
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
I have just begun learning Java and I am trying to test stuff by myself. Below is the code where I am getting an error. I am trying to call the local variable in class B in class Demo using object of class B.
public class Demo {
public static void main(String args[])
{
B obj=new B();
System.out.println("printing that variable "+obj.a);
}
}
class B{
public void test()
{
int a=10;
}
}
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation
problem: a cannot be resolved or is not a field at
Demo.main(Demo.java:7)
You can always call, but that needs to be in scope and when the current context have access to.
System.out.println("printing that variable "+obj.a);
You cannot do that since the variable a is local to the method test() and scope is restricted to that method only.
To access the way you want now, make it as a instance member.
class B{
int a; // instance member now
public void test()
{
a=10;
}
}
Now note that unless you call the method test() the default value is 0 only. Hence you might want to change your code as
public static void main(String args[])
{
B obj=new B();
obj.test();
System.out.println("printing that variable "+obj.a);
}
and if you don't want to call a method at all want to access a directly, you can do
public class Demo {
public static void main(String args[])
{
B obj=new B();
System.out.println("printing that variable "+obj.a);
}
}
class B{
public int a= 10;
}
Imp note :Always resolve all the compile errors before running your program :)
Because in
class B {
public void test() {
int a = 10;
}
}
a is local variable of test method. If what you are trying to do would be possible, what value should be used in scenario like
class B {
public void test1() {
int a = 10;
}
public void test2() {
int a = 20;
}
}
Should a come from test1 or from test2? For compiler this two methods are equally correct so it can't decide for you, which would cause the problem. Also lets not forget that method can have few variables with same name as long as they are in different scope, that is why we can have few for(int i...) methods (so from which scope you would want to use i).
Generally . operator is used to get access to member of class, not variable from method. So via object.member you may access to object.method() or object.field. If your class would look like
class B{
public int x;
public void test1() {
int a = 10;
}
}
you could use object.b since b is class B field.
Anyway if you want to get access to value of variable created and used only in method test, you could change this method to return this value. In other words you could rewrite it like
public int test1() {
int a = 10;
//... you can do something with a
return a;
}
Now in main method in Demo class you could use int result = obj.test();
If I have a constructor
public class Sample {
public static StackOverflowQuestion puzzled;
public static void main(String[] args) {
puzzled = new StackOverflowQuestion(4);
}
}
and inside the main method of a program i have
public class StackOverflowQuestion {
public StackOverflowQuestion(){
//does code
}
public StackOverflowQuestion(int a){
this();
}
}
Is this creating an instance of StackOverflowQuestion via constructor2 and then creating another instance of StackOverflowQuestion via constructor 1 and therefore i now have two instances of StackOverflowQuestion directly inside each other?
Or does constructor2 in this case kind of laterally adjust and then instead create an instance of StackOverflowQuestion via constructor1 ?
I think you mean:
public class StackOverflowQuestion
{
public StackOverflowQuestion(){ // constructor
//does code
}
public StackOverflowQuestion(int a){ // another constructor
this();
}
}
And call it like:
StackOverflowQuestion puzzled = new StackOverflowQuestion(4);
This will only create one object, because new is executed only once. The call this() will execute the code in the other constructor without creating a new object. The code in that constructor is able to modify the currently created instance.
It only creates one instance. One use case of it is to give default values for constructor parameters:
public class StackOverflowQuestion
{
public StackOverflowQuestion(int a) {
/* initialize something using a */
}
public StackOverflowQuestion() {
this(10); // Default: a = 10
}
}
this() is not the same as new StackOverflowQuestion()
this(5) is not the same as new StackOverflowQuestion(5)
this() and this(5) calls another constructor in the same class.
Therefore in this example:
public class StackOverflowQuestion
{
private int x;
private int y;
private int a;
public StackOverflowQuestion(){
this.x = 1;
this.y = 2;
}
public StackOverflowQuestion(int a){
this();
this.a = a;
}
}
The call to this() will just initialize the object and not create a new instance. Remember new StackOverflowQuestion(5) has been called already invoking the constructor which actually creates a new instance of the StackOverflowQuestion object
A constructor does not create an object. It just initializes the state of the object. It's the new operator which creates the object. Read through Creation of New Class Instance - JLS. Now what does this mean :
public class StackOverflowQuestion
{
public StackOverflowQuestion(){ // constructor
//does code
}
public StackOverflowQuestion(int a){ // another constructor
this();
}
}
StackOverflowQuestion puzzled = new StackOverflowQuestion(4);
A new object of StackOverflowQuestion is created by the new operator, just before a reference to the newly created object is returned as the result and assigned to the StackOverflowQuestion puzzled reference variable , the constructor StackOverflowQuestion(int a) makes a call to this() i.e. public StackOverflowQuestion(), code(if any) inside the default constructor runs and the control comes back to `StackOverflowQuestion(int a), the remaining code(if any) inside that is processed to initialize the new object.
The instance of a class is created at the moment you use the "new" operator. It is perfectly possible to create a class without constructors, because in that case, by default, the constructor with no parameters is available.
The "this" keyword just points to THIS specific object, so calling "this()" means "call my own constructor function, the one without parameters and execute what's inside"
This question already has answers here:
Static Classes In Java
(14 answers)
Closed 3 years ago.
So, in short. I have two classes.
package rpg;
public class Engine {
public void main(String args[]) {
Start.gameStart();
System.out.println(menuResult);
}
}
and
package rpg;
public class Start {
int menuResult = 3;
public int gameStart()
{
return menuResult;
}
public int getMenuResult()
{
return Start.menuResult;
}
}
It keeps throwing up the error 'Cannot make static reference to non-static method gameStart()'.
I'm sure I'm missing something simple, but can't find it.
Thanks!
You need to create instance of Start class and call gameStart() method on that instance because gameStart() is instance method not static method.
public void main(String args[]) {
new Start().gameStart();
..................
}
Only static methods can be accessed by using class name as perfix.
public int gameStart() <--- Instance method not static method
call it on instance
Start start = new Start();
start.gameStart();
So finally your classes should look like below
public static void main(String args[]) {
Start start = new Start();
start.gameStart();
System.out.println(start.getMenuResult());
}
public class Start {
private int menuResult = 3;
public int gameStart() {
return this.menuResult;//Don't know why there are two methods
}
public int getMenuResult() {
return this.menuResult;
}
}
first of all the main method should be
public static void main(String args[]) {
}
I assume you can have multiple games, and hence you should be able to start multiple instances so you should create a non static class that can be created and then actions performed against.
to answer your original question, you need to have a static variable that have static getters and setters..
public class Start {
private static int menuResult = 3;
public static int gameStart()
{
return menuResult;
}
public static int getMenuResult()
{
return Start.menuResult;
}
If you need the method to be static, just add the keyword static in the function definition. That would get rid of the error. But if you want to keep the class Start the way it is, then you should create an instance of Start in the main function and then call the method. Hope that helps!
you are trying to invoke a method on its class name. you should be creating a new object and invoke its method
public void main(String args[]) {
new Start().gameStart();
System.out.println(menuResult);
}
Start.gameStart() refers to a method which would be public static int gameStart() because Start is the class and not an instance of the object.
If you declare a method on an object, you need to apply it to instance of the object and not its class.
When to use static or instanciated methods ?
instanciated : whenever you need to apply the method to the object you're in. example : mycake.cook();
static : when the actions you do inside your method have nothing to do with an object in particular. example : Cake.throwThemAll();
mycake is an instance of a Cake, declared this way : Cake mycake = new Cake();
Cake is the class representing the object.
You should, i guess, have a read at some object oriented programmation course if you still have a doubt about objects, classes and instances.
While Other answers are Correct , that remains the Question that Why you Can't access Instance
method Directly from Class name , In Java all static (methods , fields) bind with Class Name and when Class Is Loading to the Memory (Stack) all static members are Loading to the Stack , and this time Instance Method is not visible to Class. instance Method will Load into Heap portion in the memory and can only be access by Object references .