This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How come invoking a (static) method on a null reference doesn’t throw NullPointerException?
Can any one explain why the output of the following program is "Called"
public class Test4{
public static void method(){
System.out.println("Called");
}
public static void main(String[] args){
Test4 t4 = null;
t4.method();
}
}
I know we can call static method with class reference , but here I am calling using null reference . please clarify my doubt
In the Byte code
Test4 t4 = null;
t4.method();
will be
Test4 t4 = null;
Test4.method();
Compiler would convert the call with the class name for static methods. refer to this question on SO which i myself have asked it.
It doesn't matter if the instance is null, because you are calling a static method.
Think of it this way.
Every static method is equivalent with a class method whereas a non-static method is equivalent with
an instance method.
Therefor it doesn't matter what value the instance takes as long as you are working with static methods or members.
Static methods can be called via the classname or an instance.
I would try to avoid to call them by an instance (also a lot of tools warn you to do so because of bad practice).
Related
This question already has answers here:
What is the purpose of a no-arg constructor?
(4 answers)
Closed 1 year ago.
1st program without constructor:
public class Sample1 {
int a=9;
public static void main(String args[]) {
Sample1 obj = new Sample1(); // I know this is a default constructor
System.out.println(obj.a);
}
}
Output: 9
2nd program with constructor:
public class Sample1 {
int a;
Sample1(){
a=9;
}
public static void main(String args[]) {
Sample1 obj = new Sample1();
System.out.println(obj.a);
}
}
Output: 9
If both the things give same output then what's the use of taking the pain to declare constructor?
For this usecase, there really isn't much of a difference. Constructors are usually useful in two scenarios:
When you want to take arguments instead of initializing the members to hard-coded values.
If you have some logic you want to run when the instance is constructed.
This is closely related, although it refers mostly to static:
Difference between the static initializer block and regular static initialization
So in a few bullet points:
Essentially, for you, they're equal
variables get initialized first, then the CTOR gets run (but be aware, with inheritance some differences may arise)
in both you can assign final variables
inside the CTOR, you can process parameters given
initiailizing inside the CTOR has the big advantage that you can handle exceptions
in variable initialization, you cannot call any method that throws a Checked Exception (derived fom Exception but not from RuntimeException
in variable initialization, you cannot control what happens when the variable initialization throws and Unchecked Exception (Throwable, Error, RuntimeException)
inside the CTOR you can also do CTOR Chaining or reference super class CTORs
This question already has answers here:
Why does this not cause a NullPointerException?
(2 answers)
Closed 3 years ago.
What is the reason for the output? I know it prints Hello World but don’t know why as it should give NullPointerException.
public class Null
{
public static void greet()
{
System.out.println("Hello World");
}
public static void main(String[] args)
{
((Null)null).greet();
}
}
This is because greet()is a static method. So
((Null)null).greet();
is equivalent to,
Null.greet()
Since greet is a static method, a class instance is not needed (and not used...) to invoke it.
The ((Null)null) expression doesn't dereference null, it simply serves as a type definition used to access the static method.
When we attempt to use an object reference that has a null value, NullPointerException is thrown. So, in your example you may think that how greet() method is successfully called from a null object.
But, look at the method signature carefully, it has a static modifier in front of it. If you call a static method on an object with a null reference, you won’t get an exception and the code will run without any exception. That is because static methods are the class methods not the instance method.
So when you compile your code, ((Null)null).greet() is simply converted to Null.greet().
For simplicity, consider the code below:
Null obj1 = null;
Null obj2 = new Null();
obj1.greet();
obj2.greet();
As greet() is a static method here, during that method call compiler will simply ignore if there is anything inside the object created from it or not. It will be just compiled as Null.greet() for both obj1 and obj2.
However, try to remove the static modifier from the method. You will find that NullPointerException you were expecting.
This is valid behaviour since :
((Null)null).greet();
will be like calling a static method greet on Null class.
It is even shown as correct behaviour in example 15.11.1-2. Receiver Variable Is Irrelevant For static Field Access of JLS :
The following program demonstrates that a null reference may be used to access a class (static) variable without causing an exception:
class Test3 {
static String mountain = "Chocorua";
static Test3 favorite(){
System.out.print("Mount ");
return null;
}
public static void main(String[] args) {
System.out.println(favorite().mountain);
}
}
And the explanation on what is happening, why it compiles and prints Mount Chocorua :
Even though the result of favorite() is null, a NullPointerException is not thrown. That "Mount " is printed demonstrates that the Primary expression is indeed fully evaluated at run time, despite the fact that only its type, not its value, is used to determine which field to access (because the field mountain is static).
So in your case that is only type of expression ((Null)null) - that is evaluated to Null - that is used to determine which method to call ( there is a static method greet in Null class so it is not a problem).
This question already has answers here:
What is a class literal in Java?
(10 answers)
Closed 5 years ago.
To illustrate the contrast. Look at the following java snippet:
public class Janerio {
public static void main(String[] args) {
new Janerio().enemy();
}
public static void enemy() {
System.out.println("Launch an attack");
}
}
The above code works very fine and seems to be yes as answer to this question as the output turns to be as follows.
Launch an attack
But at the very next moment when I run the following snippet
public class Janerio {
public static void main(String[] args) {
System.out.println(new Janerio().class);
}
}
I get the compile time error
/Janerio.java:3: error: <identifier> expected
System.out.println(new Janerio().class);}
^
/Janerio.java:3: error: ';' expected
System.out.println(new Janerio().class);}
^
2 errors
I don't see why such a situation comes up because in the previous snippet I was able to access the static "enemy" function with the help of an instance of the class but here it's proving false. I mean why can't I access the ".class" static method with the help of the instance of the class. Am I wrong to consider ".class" to be a static function or member of the class Janerio and is it wrong to be analogous to the static features of both the snippets?
But as soon as I call the ".class" with the class name things appear to be that ".class" is static in nature but it deviates to the be static on calling ".class" with an instance of the class.
public class Janerio {
public static void main(String[] args) {
System.out.println(Janerio.class);
}
}
Output we get:
class Janerio
.class references the Class object that represents the given class. it is used when there isn't an instance variable of the class. Hence it doesn't apply to your usage
Read more here:
https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.8.2
With .class you do not select a field (besides class is a keyword).
It is a pseudo operation, usable with a class name, yielding a Class instance:
int.class, Integer.class, java.util.List.class
Am I wrong to consider ".class" to be a static function or member of the class Janerio?
Yes, it's not a variable and it's definitely not a method. You have to use the Object#getClass method when you want to get the class of an instance.
Yes, you can access these static members of classes that way, but the better practise is to use name of that class instead of the name of specific referece to object of that class. It makes your code clearer to understand and to read as static members of class do not belong to specific object but to whole class. For example:
class MyClass {
static int count = 0;
}
It is better to access this field that way:
MyClass.field = 128;
instead of changing that value using the name of specific reference, for example:
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
obj1.field = 128;
Because it can be confusing when you realize that this way even obj2.field has assigned new value of 128. It might look a bit tricky, so again, I would suggest the first presented method of calling methods or changing values assigned to fields.
This question already has answers here:
What is the reason behind "non-static method cannot be referenced from a static context"? [duplicate]
(13 answers)
Closed 6 years ago.
Class1.java
public List<UMRDTO> getDocumentationList(Session session)
{
List<UMRDTO> documentationList = null;
try
{
Query query = null;
query = session.createQuery(UMRSQLInt.DOCUMENTATION_LIST);
documentationList = query.list();
}
return documentationList;
}
I need to use the documentationList that is returned to a static method in this like but getting error like non static method cannot be refrenced from static context
class2.java
static
{
UMRMetadataSupportDAOImpl d=new UMRMetadataSupportDAOImpl();
listDocuments= d.getDocumentationList(); //error here
for (UMRDocumentationDTO listDoc: listDocuments)
{
if(listDoc.equals(MMTConstantsInt.DOMAIN_NAME))
domainDocumentationMap.put(listDoc.getId().getObjectName(), listDoc.getDocumentationLink());
else
domainComboDocumentationMap.put(listDoc.getId().getObjectName(), listDoc.getDocumentationLink());
}
Static fields and methods are linked to the class. They can be invoked just by the classname and dot operator.
Non static fields and members are linked to an instance of the class. They need an object of the class to be invoked. In the same class there is a special reference which refers to the currently executing object called this.
Class is a blueprint and its instances are the realization of that blueprint. When an object is created then in memory the space is allocated. We invoke non static methods on the object.
Your method getDocumentationList is non static meaning it requires an object of class1 so that it could be invoked on that object. You are calling it using a class name instead you need to create an object and then invoke the method.
Second option is to declare getDocumentationList as static.
This question already has answers here:
Overriding member variables in Java ( Variable Hiding)
(13 answers)
Closed 6 years ago.
class A
{
protected int i=10;
}
class B extends A
{
protected int i=15;
}
public class Test extends B
{
public static void main(String a[])
{
A obj=new Test();
System.out.print("i="+obj.i);
}
}
It's output is i=10, but how?
How is the memory allocation for the object will take place.
A obj=new Test();
Means, you are accessing the members of Class A and executing the methods of Test(polymorphism).
I suggest you to read the official docs on inheritance and polymorphism to understand deep.
Polymorphism is linked to objects not references. Since you are using a reference of type A, you will get A.i if you have method getI() in A and override it in B, then call obj.getI(), then you will get B.i's value
In java, Variable Overriding is not there. We have the concept of method Overriding.
In your code
A obj=new Test();
You can able to access members of A. If you have overridden same method in both the classes (Parent and Child). And you are calling that method with obj. This time you will get output from Child class overridden method. this is the concept of Polymorphism.
Line 1: A a = new A();
the method existence will be checked in A class and the method will be called from A class also.
a.g();//A class method will be called
System.out.print("i="+a.i);//A class i will be accessed
Line 2: A b = new B();
the method existence will be checked in A class and the method will be called from B class.
b.g();//B class method will be called and it will also check that it is` available in A also or not if not then compile time error.
System.out.print("i="+b.i);//A class i will be accessed