Can we call static method via a temp variable in java [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Can we call static method via a temp variable?
There is a class AA
class AA {
static void test() {
}
}
class Main {
public static void main(String[] args) {
var aa = AA;
aa.test(); // Can we call static method via a temp vairble ?
}
}
Why I have the question? Because I must modify all the instance call style to class static style in my refactor work. The method was an instance method before and use a local variable to call it and now it became a static method or class. So I consider if there is way that just modify the variable. Maybe it's naive.
Directly, maybe like this, but not right.
Class<AA> aa = AA;
aa.test();
I know it's not good way to call static method by a instance as well.
And we know there is a way in Java 8 to refer a function. So is there another more meta capability to refer a literal class?

Can we call static method via a temp variable ?
Yes, you can. (Modulo the compilation errors!)
But you are probably not doing what you think you are doing with this. And it is a bad idea.
In fact, aa.test() actually means exactly the same thing as writing Variable.test(). That is, the value of aa and its actual type are completely ignored in determining which method is called, and in calling the method1.
The class whose test() method is invoked is resolved to Variable at compile time. Java does not support overriding or dynamic dispatching of static methods.
1 - The JLS states that the expression that computes the reference is evaluated, but the resulting reference is then discarded.
Invoking a static method via an instance variable is bad style, and should be avoided.
Consider this:
class AA {
static void test() {
System.out.println("AA");
}
}
class BB extends AA {
static void test() {
System.out.println("BB");
}
}
class Main {
public static void main(String[] args) {
AA aa = new BB();
aa.test();
}
}
Q: What is the output?
A: The output is "AA".

Actually, that is not how to call a static method from a class.
If we have class AA :
class AA {
public AA() {}
public static void test() {
System.out.println("Test");
}
}
We can call the test method like this:
AA.test();
It is not recommended to call static method from it's instance like this:
AA aa = new AA();
aa.test();

Related

Can we access static members and static functions of a class with the help of instance variables of that class in java? [duplicate]

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.

instantiation of objects of other classes in java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
i have this situation:
public class Number {
int num;
private TakeNumber take = null;
public Number() {
num = 5;
}
public void print() {
take.doSomething();
}
public int getNumber() {
return num;
}
public static void main(String[] args) {
new Number();
}
}
public class TakeNumber {
private Number number = new Number();
public void doSomething() {
System.out.println(number.getNumber());
}
}
Now, can someone explain me these situations:
I want to know what the compiler interprets here : private Number number = new Number();
Initialize the object in question and passing the required methods
Is correct initialize one object to null and then call a function on that object, as shown
in brief
I would like to know if you can call a method of a class of another class:
without the required function to be static
IMPORTANT do not inherit the classes because I want to use methods of these classes, for example:
I have classes that are conceptually different as Tomato and machine, I would call the methods of Machine into Tomato
I would like to know if you can call a method of a class of another class:
without the required function to be static
If the methods are not static, then you will need an instance of that object to call it.
Object o = new Object();
o.doSomething();
Is how you access an instance method.
I have classes that are conceptually different as Tomato and machine, I would call the methods of Machine into Tomato
This is fine. This is called composition. Composition is a has a relationship between classes. A class Man has a class Car, but Is a class Person. And it is perfectly valid to write code as you have shown. This is how you use composition to expose only the interface of a composite object that you want. For example..
public class MyClass extends MyOtherClass
Now you've just exposed the whole interface of MyOtherClass. This might not be desired.
public class MyClass {
MyOtherClass otherClass;
public void doSomething() {
otherClass.doSomething();
}
}
Now, you've only exposed the doSomething() method. This is useful when, as you said, your objects are conceptually different, but require some shared functionality. It is a perfectly valid code practise.
NOTE: Given the confusing nature of your question, I imagine I've missed some stuff out so please comment with desired edits.

Null value after constructor [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
class test
{
public static myclass x;
test() {
try {
x=new myclass();
//x is not null here
} catch(Exception e) {/*stuff*/}
//not null here
}
//x is null here in any other member method
}
Please explain a reason for this behavior?
Isn't a constructor required to retain a value rather than losing it once a constructor block ends?
You seem to be confusing static values with instance values.
x is static, but it's not initialized in a static initialization block. It's only initialized when you create an instance of test (via the constructor for that instance). Also note that it's going to be re-initialized any time you create a new instance of test, which is probably going to cause some very strange bugs for you.
In order for x to be initialized as a static value for the class, add it to a static initialization block:
class test
{
public static myclass x;
static
{
x=new myclass();
}
}
This way x should only be initialized once, statically, when the runtime loads the class. This would allow it to be accessed without first having to create an instance of test, as well as remove the bug of re-initializing it on any new instance of test.
Conversely, if this should instead be an instance value instead of a static value, you can simply change its declaration:
public myclass x;
as such code is correct. but since the variable x is static, you might be accessing it before calling the constructor. in that case it will be null. As soon as, the constructor get to run for the first time, the value of x will be set to a new object.
if its you requirement to keep x static. initialize it in static initializer block. like:
class test
{
public static myclass x;
static {
x = new myclass();
}
}
or simply as:
class test
{
public static myclass x = new myclass();
}

why java does not support dynamic variable dispatch [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Please excuse me if title is wrong. There are two class Test and TestChild1 where TestChild1 is inherited from Test. Both classes have a variable named "a". When I tried to access variable "a" through superclass variable which is instantiated with subclass object, it is giving the value that is initialized with in superclass not subclass.
following is the code that raised the doubt
class Test {
public int a = 10;
}
class TestChild1 extends Test {
public int a = 20;
}
class Main {
public static void main(String args[]) {
Test test = new TestChild1();
System.out.println(test.a); // results in 10
}
}
Please give me the reasons for this behavior. Thanks in advance....
Because the Java designers decided to make methods polymorphic (and thus overridable), but not fields.
When you reference a field from an object, the compiler decides which field to use, based on the declared type of the variable, which, in this case, is Test.
When you refer to methods, the JVM, at runtime, chooses which method to call based on the actual, concrete type of the object which, in this case, is TestChild.
OO is all about encapsulation of state, so you should almost never expose fields to the outside anyway.
The class TestChild1 has two variables with the same name. If you access them through Test you get the first one, from TestChild1 you get the second one.
To get your expected result, you should not declare a in the derived class. Instead you should initialize it in the costructor of the derived class.
You declared your object as Test, not the subclass. At compile time that means you refer to the base class which has 10.
Because behavior is associated with methods and not with fields.
So, fields have static binding (in this case this, since test is of type Test, value of a is assigned with value 10). Whereas methods have dynamic binding.
Since, the variable a doesn't define the behavior of Test class, it is assigned the value as per its type and not as per its instance.
JB Nizet have already said everything, but I will add this code for more understanding:
class Test {
private int a = 10;
public int getA() {
return a;
}
}
class TestChild1 extends Test {
private int a = 20;
public int getA() {
return a;
}
}
class Main {
public static void main(String args[]) {
Test test = new TestChild1();
System.out.println(test.getA()); // results in 20
}
}
So if you would encapsulate your fields, you would have expected behaviour.

calling static method in java [duplicate]

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).

Categories

Resources