Logo 
Search:

Java Answers

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds
  Question Asked By: Violet Nelson   on Oct 22 In Java Category.

  
Question Answered By: Mansur Bashara   on Oct 22

A non-static variable describes a property of a particular object, while a
static variable describe a property of the entire class. That's the whole thing
you must keep in mind.

Example: Let's imagine the class  of all pens of a given color.

public class SameColorPen
{
private static  String color = "red"; // this will be the same for all the
objects
private int size; // this will be different for all the objects

public SameColorPen(int size)
{
this.size = size;
}

public static String paint(String newColor)
{
String oldColor = color;
color = newColor;
return oldColor;
}
}

SameColorPen pen1(10); // red pen of size 10
SameColorPen pen2(20); // red pen of size 20
String oldCol = SameColorPen.paint("blue"); // this paints all the objects  of
this class in blue. pen1 and pen2 will be blue from now on.
SameColorPen pen3(30); // blue pen of size 30

Now take a closer look at the paint method  body. Inside a static method, only
static members of the class can be refered. But you are free to create and use
any other object. In the example, I declared a String object. This object  will
not be over-anything each time  the paint method is called, because it is created
and destroyed with each call, like any variable inside a block.

Share: 

 

This Question has 3 more answer(s). View Complete Question Thread

 
Didn't find what you were looking for? Find more on instantaite objects from frequently called static methods Or get search suggestion and latest updates.


Tagged: