About static and non-static

  • (2 Pages)
  • +
  • 1
  • 2

17 Replies - 3724 Views - Last Post: 08 August 2012 - 01:36 AM Rate Topic: -----

#1 John-acme  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 65
  • Joined: 08-February 11

About static and non-static

Posted 06 August 2012 - 02:35 AM

Here I don't understand about static and non-static.. up til now I know, if something said to be static then it's value cannot be change(more likely a constant)..
I learn Java by autodidact..
Here the code:
public class CubicToy {
    private double side;
    /* Creates a new instance of CubicToy */
    public CubicToy(double side) {
        this.side = side;
    }
   
    static void test (){
        CubicToy m = new CubicToy(3.5);
        System.out.println(m);
        System.out.println("This cubic has circumference for each side of "+m.getCircumference(3.5));
        System.out.println("This cubic has Area for all side of "+m.getAllArea(3.5));
        System.out.println("This cubic has Volume of "+m.getVolume(side));       // here the 1st error
    }
    public String toString (){
        String str = "This cubic has "+ side + " side lenght";
        return str;
    }
    
    public double getCircumference(double side){
        return side * 4;
    }
    
    public double getAllArea (double side){
        return side * side *6;
    }
    
    public double getVolume (double side){
        return side*side*side;
    }
    
    public static void main(String args[]){
        test(); // here 2nd error
    }   
}


if I compile codes above, I get error(1st error) non-static variable side cannot be referenced from a static context

so I try to change the function of
static void test()
into
void test()
..
and the result if I compile become (2nd error): non-static method test() cannot be referenced from a static context

next again I try to change
public static void main(String args[])
into
public void main(String args[])
.. and the result of compile is SUCCESS .. BUT if I run/debug it.. pop-up a message dialog which it's said that Class "CubicToy" does not have a main method.

can someone explain to me why it can work like that?
I have knew that this error can be solveed if I change
m.getVolume(side)
into
m.getVolume(3.5)
..but I just don't understand why I can not use
m.getVolume(side)

Thanks in advanced for the explaination..

Is This A Good Question/Topic? 0
  • +

Replies To: About static and non-static

#2 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2203
  • View blog
  • Posts: 5,235
  • Joined: 10-September 10

Re: About static and non-static

Posted 06 August 2012 - 02:50 AM

In short, a static method, variable, etc. doesn't require an instance of that class to be used to access it. This is especially important in the main() method, because main() is used as the starting point for Java programs. If an instance of a class were required to access the program's starting point, then a Java program would never be able to start.

The concept of static you mention from your previous experience is equivalent to 'final' in Java. In Java, static is associated with being outside or not requiring an instance of a class to be accessed.

So, the error most experience as they struggle to understand this concept, "non-static variable side cannot be referenced from a static context," means that the variable 'side' requires access through an instance of the class. It cannot be accessed statically, without the class instance:

SomeClass someClass = new SomeClass();

someClass.side; // <-- accessing the variable through an instance of the class

Edit: eliminated confusing 'it'

This post has been edited by GregBrannon: 06 August 2012 - 02:51 AM

Was This Post Helpful? 2
  • +
  • -

#3 smohd  Icon User is offline

  • Critical Section
  • member icon


Reputation: 1819
  • View blog
  • Posts: 4,627
  • Joined: 14-March 10

Re: About static and non-static

Posted 06 August 2012 - 02:57 AM

Quote

if something said to be static then it's value cannot be change(more likely a constant)..

Wrong, in java static means something that is shared by all instances. So if you have an instance variable, its value will be shared by all instances of that class, and a change will affect all objects.

Again, you cant change the main() method, it must remain with that definition:
 public static void main(String arg[])

So removing the static keyword will make the jvm to not find the main().

Also the error which says: non-static variable side cannot be referenced from a static context means that, in java you cant call a non static variable/method from a static context. That is if a method is static, it cant call a non static method directly or use a non static instance.

Now test must be static there to be called in main, or you have to create an object of CubicToy first and then use it to call test() method.
Was This Post Helpful? 2
  • +
  • -

#4 John-acme  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 65
  • Joined: 08-February 11

Re: About static and non-static

Posted 06 August 2012 - 03:11 AM

Ouh.. if that so.. then that's why for function main() and function test() need static in their prefix, because instance only can be declared after main executed.. and in my case, in main didn't declare any instance, but just call the function test. To able to call test without any instance exist, then function test also need to be static... Is my understanding true?

If yes, then instead declared variable side by using private double side, I can change it into private static double side.. I had tried this resolve and the code works...

then Are there any bad side effect if I use private static double side, instead of private double side ??

Thanks^^
Was This Post Helpful? 1
  • +
  • -

#5 John-acme  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 65
  • Joined: 08-February 11

Re: About static and non-static

Posted 06 August 2012 - 03:31 AM

I tried to create instance of CubicToy first in main() method and then I call test() method by using the instance. Here the code become:

public class CubicToy2 {
    private double side;
    /* Creates a new instance of CubicToy */
    
    public CubicToy2(double side) {
        this.side = side;
    }
    
    void test (){
        System.out.println(m);   //here error
        System.out.println("This cubic has circumference for each side of "+m.getCircumference(3.5)); // here error
        System.out.println("This cubic has Area for all side of "+m.getAllArea(3.5));  //here error
        System.out.println("This cubic has Volume of "+m.getVolume(side));  //here error
    }
    public String toString (){
        String str = "This cubic has "+ side + " side lenght";
        return str;
    }
    
    public double getCircumference(double side){
        return side * 4;
    }
    
    public double getAllArea (double side){
        return side * side *6;
    }
    
    public double getVolume (double side){
        return side*side*side;
    }
    
    public static void main(String args[]){
        CubicToy2 m = new CubicToy2(3.5);
        m.test();
    }   
}


But 4 same error come out,:
cannot find symbol
symbol : variable m
location: class CubicToy2
System.out.println(m);


Why after I declare an instance in main() named m, the instance m cannot be recognized in test() method??

Thanks..
Was This Post Helpful? 0
  • +
  • -

#6 smohd  Icon User is offline

  • Critical Section
  • member icon


Reputation: 1819
  • View blog
  • Posts: 4,627
  • Joined: 14-March 10

Re: About static and non-static

Posted 06 August 2012 - 03:41 AM

Why do you want to print m anywhay?
It is local variable in main() and cant be accessed in any other method, it basic variable scope issue there that you cant access a variable outside its scope
Was This Post Helpful? 0
  • +
  • -

#7 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5874
  • View blog
  • Posts: 12,752
  • Joined: 16-October 07

Re: About static and non-static

Posted 06 August 2012 - 04:21 AM

The ONLY method in your program that must be static is main. Because everything has to start somewhere. However, you don't need any static after that and, if you're just learning, you're best off avoiding it entirely.

public class CubicToy2 {
	private double side; /* this is the only variable accessable globally withing the object */

	/* Creates a new instance of CubicToy */
	/* not exactly, the constructor is called when another part of the program creates a new instance */
	public CubicToy2(double side) {
		this.side = side; // note, you assign the value to the instance variable
	}

	public String toString (){
		// this is correct, you're using this.side implicitly
		return "This cubic has "+ side + " side lenght";
	}

	// this is incorrect
	// why are you passing a side value when the instance has one?!?
	// public double getCircumference(double side){
	// instead, use the side you have
	public double getCircumference(){
		return side * 4;
	}

	//public double getAllArea (double side){
	public double getAllArea() { return side * side * 6; }

	public double getVolume() { return side*side*side;  }

	// this should be public if you want to call it from outside
	// void test () {
	public void test () {
		// System.out.println(m);   //here error
		// of course this is an error!
		// I don't see a variable m in the scope of this instance
		// do you?
		// we could make one, if you really wanted it
		CubicToy2 m = this;
		// there, now m is this instance

		System.out.println(m);

		// but we really don't need m
		// and we don't need to pass variables about
		/*
		System.out.println("This cubic has circumference for each side of "+m.getCircumference(3.5)); // here error
		System.out.println("This cubic has Area for all side of "+m.getAllArea(3.5));  //here error
		System.out.println("This cubic has Volume of "+m.getVolume(side));  //here error
		*/
		// we explicitly call the object's method
		System.out.println("This cubic has circumference for each side of " + this.getCircumference() );
		
		// we implicitly call the object's method
		System.out.println("This cubic has Area for all side of "+ getAllArea(3.5));
		System.out.println("This cubic has Volume of " + getVolume());
	}

	public static void main(String args[]){
		CubicToy2 foo = new CubicToy2(3.5); // not to be confused with m
		foo.test();
	}   
}



Hope this helps.
Was This Post Helpful? 2
  • +
  • -

#8 John-acme  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 65
  • Joined: 08-February 11

Re: About static and non-static

Posted 06 August 2012 - 04:25 AM

Ok thanks for the explaination.. actually.. from you explaination pop up another question.. but I think it's too far for now.. so I'll keep it for later..

thanks to all for the helps..
Was This Post Helpful? 0
  • +
  • -

#9 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 7869
  • View blog
  • Posts: 13,347
  • Joined: 19-March 11

Re: About static and non-static

Posted 06 August 2012 - 07:43 AM

View PostJohn-acme, on 06 August 2012 - 05:11 AM, said:

Ouh.. if that so.. then that's why for function main() and function test() need static in their prefix, because instance only can be declared after main executed.. and in my case, in main didn't declare any instance, but just call the function test. To able to call test without any instance exist, then function test also need to be static... Is my understanding true?


Yes, I think so. A static method can create an instance of an object, which may be an object of its class or of some other class, and then it can ask that instance to execute some of its public methods. It can't execute any instance methods without an instance to call on.


Quote

If yes, then instead declared variable side by using private double side, I can change it into private static double side.. I had tried this resolve and the code works...
then Are there any bad side effect if I use private static double side, instead of private double side ??


One bad side effect would be that this class can only have one value for side. So if you multiply toys, they're all the same size.

This post has been edited by jon.kiparsky: 06 August 2012 - 07:43 AM

Was This Post Helpful? 1
  • +
  • -

#10 John-acme  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 65
  • Joined: 08-February 11

Re: About static and non-static

Posted 06 August 2012 - 11:29 PM

To Mr/Mrs. baavgai , sorry I don't know which one to be used to call..
I try to understand your guide.. but I got some part that I didn't understand fully.
Here:
public String toString (){
		// this is correct, you're using this.side implicitly
		return "This cubic has "+ side + " side lenght";
	}

	// this is incorrect
	// why are you passing a side value when the instance has one?!?

This method I use just to show/said that the CubicToy has size of 3.5 for it's length. I don't understand why you said that I used this.side implicitly? Actually above code is no problem if I have only one object named foo. But how about if I have multiple Toy - I want to printout each object's size - then it become a problem to me because I don't know how to call each CubicToy's variable(instance variable). Let say if I create a instance in this method (let's named it foo2), is not that new instance (foo2) different from previous instance (foo) created in main() method??

Then your question why am I passing a side value when the instance has one?!? . Actually I don't want to, I want to use what instance have (which I had assigned earlier). But I don't know how..

// public double getCircumference(double side){
	// instead, use the side you have
	public double getCircumference(){
		return side * 4;
	}

	//public double getAllArea (double side){
	public double getAllArea() { return side * side * 6; }

	public double getVolume() { return side*side*side;  }


this part I understand, I understand your code.. I had known this way. But I want this 3 method's return value depend on instance variable not on global assigned variable. Because If I has multiple Toy then side variable cannot contain each different value. For that purpose, I make a parameter for the method.

Next in void test() method.
CubicToy2 m = this;
		// there, now m is this instance

I don't understand this is refer to which instance, especially if I have multiple instance created.??

The rest I understand..
PS : I know this question supposed to be a new question/topic. But I know that this question may seems silly because it's still very basic, and I embarrassed if I have to post it into new topic, ..
Thanks to all that helping me.. it's really help me. each answer lead me to new understanding.
Was This Post Helpful? 0
  • +
  • -

#11 smohd  Icon User is offline

  • Critical Section
  • member icon


Reputation: 1819
  • View blog
  • Posts: 4,627
  • Joined: 14-March 10

Re: About static and non-static

Posted 07 August 2012 - 12:10 AM

The this keyword is used to reference the current instance of the class, that means by saying this.side I am referring to the side the current cube has. But sometime I can ignore the keyword this and just say side, if there is no local side created in that scope, it will mean the samething as saying this.side. So we say this is added implicitly.

Quote

But how about if I have multiple Toy - I want to printout each object's size - then it become a problem to me because I don't know how to call each CubicToy's variable(instance variable).

You dont need to worry about that because you your side is an instance variable, which means every object(instance) will have its own value of side in its heap. So if foo calls toString(), it will print its side and foo2 its own side value.
Look at how you declared your instance variable:
private double side; //this is an instance variable, every object will have its own copy of that

Now that is the concept of instance variable, you dont need to worry about passing those values, because by saying side in that method will give the value of the object that calls that method, as what baavgai was showing you.

Quote

Actually I don't want to, I want to use what instance have (which I had assigned earlier). But I don't know how....
But I want this 3 method's return value depend on instance variable not on global assigned variable.

And that is what you will get because that is what instance variables are for, every object has its own copy of it and you dont need to bother passing it, The variable know its own value
There is no global assignment there, unless a variable is declared with static keyword, it cant be shared. Static variables are the one shared by all instances of the class and not instance variables.

Quote

I don't understand this is refer to which instance, especially if I have multiple instance created.??

The current instance, the instance that calls the method!
Hope that will help
Was This Post Helpful? 1
  • +
  • -

#12 John-acme  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 65
  • Joined: 08-February 11

Re: About static and non-static

Posted 07 August 2012 - 12:40 AM

The explanation of this keyword. to me it sound like.. using this.side is same to using side only.. Correct me if I am wrong in understanding it..

If yes, then it's make no difference in using this and not using this..??? is that true? correct me again if I am wrong..

Below part of answer, I can understand well.. Thanks..
Was This Post Helpful? 0
  • +
  • -

#13 smohd  Icon User is offline

  • Critical Section
  • member icon


Reputation: 1819
  • View blog
  • Posts: 4,627
  • Joined: 14-March 10

Re: About static and non-static

Posted 07 August 2012 - 12:55 AM

Yes and no. Depending on the location of it, sometimes it mus explicitly added.
Look at this example:
public class AboutThis{
   private int myInt;
   public AboutThis(){
       myInt = 10; //here saying this.myInt or myInt will have the same effect
   }

   public AboutThis( int myInt) {
     this.myInt = myInt; // here thhose two are different
   }
}

Looking at the first constructor, in that scope there is no any myInt local variable. So if I leave the this keyword, it will be added implicitly.
But at the second constructor, the passed parameter has the same name as the instance variable. So we have local myInt and the instance one. So if there I say:
   public AboutThis( int myInt) {
     myInt = 10; // the value will no be assigned to the instance variable, but to the local one
   }

So in those locations, to reference the instance variable, I must explicitly put the this keyword. Now this statement:
this.myInt = myInt;

The myInt in left is the instance variable declared at the class level and the one in right is the passed parameter. So here we assign the passed value to the instance variable.
Is that clear now?
Was This Post Helpful? 2
  • +
  • -

#14 John-acme  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 65
  • Joined: 08-February 11

Re: About static and non-static

Posted 07 August 2012 - 02:36 AM

Hm.. so I can say that..

If a variable which the only one variable in a method (there are no any other variable with same name), then the Java treat that variable as instance variable(or treat the variable with this keyword).

If there are 2 or more variable in a method, then we must explicitly mark the variable to which instance it belong to. (using this keyword) If NOT, then the value we assigned will go to variable which declared on class level (in above code-> private int myInt)..

If like that.. I think it's better to mark the variable to certain instance than let it be default treatment by Java. (To eliminate later confusing code)^^

Thanks.. ^.^
Was This Post Helpful? 0
  • +
  • -

#15 smohd  Icon User is offline

  • Critical Section
  • member icon


Reputation: 1819
  • View blog
  • Posts: 4,627
  • Joined: 14-March 10

Re: About static and non-static

Posted 07 August 2012 - 02:55 AM

I am not sure if what I explained is what you are saying here!!!

Quote

If a variable which the only one variable in a method (there are no any other variable with same name), then the Java treat that variable as instance variable

Nop, unless it was declared in class scope as instance variables

Quote

If there are 2 or more variable in a method, then we must explicitly mark the variable to which instance it belong to
.
I am talking about two variables with different scopes here, if they have the same scope an error will occur! And we dont mark the instance it belong to, we differentiate between local method variables and class scope instance variables...

May be you may need more reading than what I can explain:
The this keyword
Understanding Instance variables

This post has been edited by smohd: 07 August 2012 - 02:56 AM

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2