static object references and non static object references - java

What is the difference between the static object references and the non-static object references ?
class example{
int r =10;
void output(){
System.out.println("The value is "+r++);
}
}
public class Test{
static example q,w,e;
public static void main(String[] args) {
q = new example();
q.output();
w = new example();
w.output();
e = new example();
e.output();
example r,t,y;
r = new example();
r.output();
t = new example();
t.output();
y = new example();
y.output();
}
}
While running this code the output of this code is same .So the question arises that what is usage of declaring a static reference variable in code and what is the difference between these static and nonstatic reference variable in java.

A static variable can be accessed from other methods of the same class, or even from other classes (if it's public). The non static variables in your code a local variables, and they are only accessible to the main method, in which they are declared.
The output is the same since you call your output method each time for a difference instance of the example class. In each of them r is initialized to 10, so r++ returns 10.

This objects are bonded with class level. It will create the example q, w, e when your class loaded. Then objects will be assigned to p, q, w when you run the method. Then you can access that objects with class reference.
example.q or example.getq() //need to create getq static method
without creating Test object.

A static variable is shared within all instances of a class and will always remain the same, a non static variable is specific to a single instance of the class.

You are creating object of one class into another so which type of object you're creating will not affect to the value of instance. The JVM always return the same type of object with its instances.

Related

Can a Variable be initialized inside a Class in Java? What about Static Variable? If yes, then what's the use for Static Block?

In C++(prior to C-11), we needed to initialize the variables outside the Class either through constructors or some methods. What's happens in Java?
Can a Variable be initialized inside a Class in Java?
Yes, like this:
public class MyClass {
private int myVariable = 10;
}
What about Static Variable? If yes, then what's the use for Static Block?
Yes, static variables can be initialized in the class as well:
public class MyClass {
private static int myVariable = 10;
}
Static blocks are used when you want to initialize a static variable, but one line is insufficient. For example:
public class MyClass {
private static HashMap<Integer, Integer> myMap;
static {
myMap = new HashMap<>();
myMap.put(10, 20);
myMap.put(20, 40);
}
}
c++ v/s Java:
Common- both OOP language
difference- c++ is not purely object oriented language, but Java is purely oop language.
Classes are blueprint(like a general map) which defines some attributes/properties(Member variables) and behavior(member functions) of a object of that class.
Class is just a imagination before creation of a object.
Object is real time entity that has physical existence in real world or in simply it's a implementation of class.
Classes in java:
class class_name
{
member variables;
member functions;
};
Ex.
class A
{
int a;
void funct()
{
//body
}
}; //defination is closed with semicolon
but,
classes in java:
ANSWER to ur quesion:
class class_name
{
member variables; //still we define the attributes in class that may be static or non-static
member functions;
};
Significance of static variable:
static variable is alloacated the common memory in ram for all the objects of that class and operation perform by any object on static member is reflected to all other object's static member because of common(same) memory.
significance of static method(functions are called methods in java): static method of a class is a method which is called without creating the object of that class.
In java, main() method is declared as static because after execution of program main() method is called without creating the object of class.
kernal of OS calls the main() method.
Can a Variable be initialized inside a Class in Java?
Yes.
class TestClass {
int abc = 0;
static int def = 1;
}
What about Static Variable?
Yes, you can. Same Example as above.
But this won't be initialized every time an object of the class is created.
TestClass ob1 = new TestClass();
ob1.def = 2; // Always use the class name to access static variables. This is just an example.
TestClass ob2 = new TestClass();
System.out.println(ob2.def); // Output : 2
PS : Always use the class name to access static variables. This is just an example.
What's the use for Static Block?
If the initialization of static variables is complex, then you can create a static block and initialize those variables there. Here is a good reference for the same.
class TestClass {
int abc = 0;
static int def = 1;
static {
int x = 100;
int y = 20;
def = x - y + 10;
}
}
If you wat to initialize the variable you can create something like
public class Animal
{
int age = 21;
static int roll = 23;
}
But remember the difference between instance variables and static variables,
int age - this variable is created for each object you create
static int roll - this variable is created only once and is one for every other object.

Why should data fields be static and final

Deitel's How To Program Java book says:
A final field should also be declared static if it is initialized in its declaration to a value.
Why is that?
public class A
{
private final int x = 5;
private static final int y = 5;
}
I think x and y are the same.
What does the static qualifier matter here?
What is the advantage of the static qualifier up there for software engineering observation?
x is an instance variable while y is global.
What does that mean?
Let's look at this example:
public class A {
public A() {
System.out.println("create A");
}
}
public class B {
public B() {
System.out.println("create B");
}
}
public class C {
private static B b = new B();
private A a = new A();
}
Then a main:
public static void main(String[] args) {
C c1 = new C();
C c2 = new C();
}
Which prints:
> create B
> create A
> create A
c1 and c2 shares the same instance of B while they both create their own instance of A!
So c1.b == c2.b while c1.a != c2.a.
So summary:
there is only one and the same place/address for field b for every instance of class C (c1, c2)
but for field a there are different places/addresses in the different instances.
The example is a bit oversized with class A and B:
Even for simple fields (int, float, ...) is one and the same place/occurrence for a static field in every instance of a class.
Since it is final, it will always hold the same value.
If you don't declare it static, you will create one variable for each instance of your class. Being static means you declare the variable only once, avoiding unnecessary memory usage.
Declaring a variable as static is more memory effecient. In your example for instance, no matter how many times you create a new A(), because fields x and fields y have been declared static, they will only be allocated memory once. If you do not declare them as static, they will be allocated memory with every new class instance.
It is sensible to declare a final variable that has been initialized like yours as static because it is not able to change, and thus allocating it memory just one time is acceptable.
Essentially, it's to save memory. If the constant is always the same no matter what, then you might as well make it static so that it doesn't get created for each object. You don't want to make it static, however, if the constant is not necessarily the same for each object (for example, if your constant is initialized somewhere in a constructor).
It saves memory as it only allocates for 1 copy of the variable. If you were to make a new instance for a non-static variable for it will make a new copy for that specified instance.
Since they are final they cannot be changed so it would make sense to make them static, so when you make new instances, nothing new is allocated for the variables since they can't even be altered.

Why can't i use static variable in java constructor?

The compiler says illegal modifier for parameter i.
Please tell me what I'm doing wrong. Why can't I use a static variable in a Java constructor?
class Student5{
Student5() {
static int i = 0;
System.out.println(i++);
}
public static void main(String args[]){
Student5 c1 = new Student5();
Student5 c2 = new Student5();
Student5 c3 = new Student5();
}
}
Because of where you are declaring i:
Student5(){
static int i=0;
System.out.println(i++);
}
the compiler treats it as a local variable in the constructor:
Local variables cannot be declared as static. For details on what modifiers are allowed for local variables, see Section 14.4 of the Java Language Specification.
Judging from what the code appears to be trying to do, you probably want i to be a static member of Student5, not a local variable in the constructor:
class Student5{
private static int i = 0;
Student5(){
System.out.println(i++);
}
. . .
}
If you want to declare static variable then declare it outside of the constructor, at class level like this -
public class Student5{
private static int i;
}
You declaration of static occurred at your constructor which is a local variable and local variable can not be static. And that's why you are getting - illegal modifier for parameter i. And finally for initializing static variable you may use a static initialization block (though it's not mandatory) -
public class Student5{
private static int i;
static {
i = 5;
}
}
This is how the language was designed.. What if you wanted to have another int field named i in the constructor?, then which i should be considered?. Also, static fields are initialized before the constructor is called i.e, during class initilization phase. A constructor gets called only when a new instance is created.
Imagine what would happen (supposed to happen) if you load and initialize a class but not create a new instance.
Static variables are variables that can be referenced without having an instance of the class. By defining one instead of a constructor, which is called when you create an instance of the class, you are contradicting yourself. Either make it defined without having an instance (outside of the constructor and static) or make it specific to an instance (inside the constructor and not static).
You might want to rethink what you are actually trying to do and if you really need a static variable.

why cannot a static method directly access a value changed by a non static method

public class JustPractice {
public int points=0;
public static void main(String args[]) {
JustPractice ha = new JustPractice();
ha.end();
happy();
}
public void end() {
this.points=100;
System.out.println(points);
}
public static void happy() {
JustPractice object = new JustPractice();
System.out.println(object.points);
return;
}
}
The above is displaying:
100 0
whereas it should be displaying:
100 100
You are looking at two different instances of your class.
Every instance gets their own copy of the instance fields, and they are completely independent from each-other.
JustPractice ha = new JustPractice();
ha.end(); // this one has "100"
JustPractice object = new JustPractice(); // this one has "0"
System.out.println(object.points);
The static method can only access ha's instance fields if you provide it with a ha as a parameter.
Make points static. Then you got what you want.
public static int points=0;
make points static will keep only one variable for all instance of your class.
Else each initialization will create separate individual variable and will assign the value to 0
its because of when method is making new object then that time it will having another copy as of the reference object will be having independent copy per object of the class remember the java basic?
and if u will make int as static object then it will give your output what u want and what u asking for simple example from yours is
public static int points = 0;
public void end() {
this.points = 100;
System.out.println(points);
}
public static void happy() {
CheckingClass object = new CheckingClass();
System.out.println(object.points);
return;
}
public static void main(String args[]) {
CheckingClass ha = new CheckingClass();
ha.end();
happy();
}
hope it helpful
it is displaying as 100 0 instead of 100 100 because you are creating a new instance of class JustPractice in your happy() method, instead of passing reference i.e. ha of existing instance.
new newly created instance is showing the default value that that u have given in your class, i.e. 0.
You set value of the points instance variable in end method.and for the object in happy method you don't initialize the points instance variable of object.
So it gets the default value 0.
A static method can access a non-static object, but only if it is passed to the method. Given that the static method in question is the method in which the program begins, you have no ability to pass anything to it.
What it cannot do, within the scope of a non-static class, is access any of the instance members or functions. The problem is not that you're instantiating ha from a static method, it's that you're accessing the member points, which is an instance member that belongs to every instantiation of your class.
In order to fix this, you can either pass points to the instance of JustPractice (ha) that you're creating, and have one of JustPractice's methods return the final value, or you can make points, end() and happy() static as well, in which case all can work happily with one another.

Static methods and static fields in Java behave somewhat in a strange way

By convention, a static method specifically in Java can have access only to static fields or other static methods. The following simple code snippet however appears to violate the convention. Let's consider the following simple code snippet in Java.
class Super
{
protected static int x;
protected static int y;
public Super(int x, int y)
{
Super.x=x;
Super.y=y;
}
public static int sum()
{
return(x+y);
}
}
final class Sub extends Super
{
public static int temp=100;
public Sub(int x, int y)
{
super(x, y);
}
public void concreateMethod()
{
System.out.println("\nInstance variable x = "+x);
System.out.println("Instance variable y = "+y);
}
}
final public class Main
{
public static void main(String[] args)
{
Sub s=new Sub(10, 5);
System.out.println("\nAssociating with object x = "+s.x);
System.out.println("Associating with object y = "+s.y);
System.out.println("\nAssociating with class name x = "+Sub.x);
System.out.println("Associating with class name y = "+Sub.y);
System.out.println("\nSummation (Associating with object) = "+s.sum());
System.out.println("Summation (Associating with class name) = "+Sub.sum());
System.out.println("\nAssociating with class name temp = "+Sub.temp);
System.out.println("Associating with object temp = = "+s.temp);
System.out.println("\nConcreate method called.");
s.concreateMethod();
}
}
The above code produces the following output with the respective statements.
Associating with object x = 10
Associating with object y = 5
Associating with class name x = 10
Associating with class name y = 5
Summation (Associating with object) = 15
Summation (Associating with class name) = 15
Associating with class name temp = 100
Associating with object temp = = 100
Concreate method called.
Instance variable x = 10
Instance variable y = 5
The static fields s and x are being accessed through the following statements within the main() method using the object of the Sub class, though they are declared as static in the super class Super.
Sub s=new Sub(10, 5);
System.out.println("\nAssociating with object x = "+s.x);
System.out.println("Associating with object y = "+s.y);
The following statements of course, have no doubt.
System.out.println("\nAssociating with class name x = "+Sub.x);
System.out.println("Associating with class name y = "+Sub.y);
Since x and y are static, they can certainly be accessed in this way.
The same is the method call, observe the following statements.
Sub s=new Sub(10, 5);
System.out.println("\nSummation (Associating with object) = "+s.sum());
System.out.println("Summation (Associating with class name) = "+Sub.sum());
Both of the ways, the static method sum() is being accessed using the object of the class Super and also using the class name Sub.
Again the similar case with the static field temp declared within the Sub class
System.out.println("\nAssociating with class name temp = "+Sub.temp);
System.out.println("Associating with object temp = = "+s.temp);
The static field temp is being accessed in both the ways.
Why is this happening here?
Basically it's a flaw in the design of Java IMO which allows static members (methods and fields) to be referenced as if they were instance members. This can be very confusing in code like this:
Thread newThread = new Thread(runnable);
newThread.start();
newThread.sleep(1000);
That looks like it's sending the new thread to sleep, but it actually compiles down into code like this:
Thread newThread = new Thread(runnable);
newThread.start();
Thread.sleep(1000);
because sleep is a static method which only ever makes the current thread sleep.
Indeed, the variable isn't even checked for non-nullity (any more; it used to be, I believe):
Thread t = null;
t.sleep(1000);
Some IDEs can be configured to issue a warning or error for code like this - you shouldn't do it, as it hurts readability. (This is one of the flaws which was corrected by C#...)
There is no problem there. Static methods can only access static fields and call other static methods as you have stated. Nothing in your examples does otherwise.
Non-static methods can access both static and non-static methods and fields. Again, none of your examples violate that.
The Sub.temp and s.temp are equivalent and you can use both, it means the same. But 1st is better one because suggests it's a static field.
a static method specifically in Java can have access only to static fields or other static methods declared within the same class
Or its superclass.
I don't see any violation here, you can access static fields/methods via its concrete object or class name. both refer to the same thing.
Where do you see a non-static field or method being accessed by static code? Everything seems perfectly fine to me.
Perhaps what's confusing you is that static fields and methods can be accessed through instances as well as through the class name? It's certainly a big ugly and many consider it bad design, but that's all.

Categories