Reputation: 1889
I have a Base class
public class BaseStatic {
public static String fname = "Base";
public static String lname = "Static";
public static void send(){
System.out.println("BaseStatic send");
sendTo();
}
public static void sendTo(){
//How to call from here Child's static method.
System.out.println("BaseStatic sendTo");
}
}
and I have a Child Class which extends it.
public class FirstStatic extends BaseStatic {
public static String fname = "First";
public static String lname = "Static";
public static void sendTo(){
System.out.println("FirstStatic sendTo");
}
}
Now there is an Main class
public class Main {
public static void main(String args[]){
FirstStatic.send();
}
}
Does java provide me a way so that when i call from Main method FirstStatic.send , It goes to send method of BaseStatic , from there i can call sendTo method of FirstStatic rather than calling sendTo method of BaseStatic
Upvotes: 4
Views: 3083
Reputation: 2826
The commented-out sendTo() method here would have the effect of hiding the implementation of sendTo() in the base class.
public class BaseStatic {
public static String fname = "Base";
public static String lname = "Static";
public static void send(){
System.out.println("BaseStatic send");
sendTo();
}
public static void sendTo(){
//How to call from here Child's static method.
System.out.println("BaseStatic sendTo");
}
public static void main(String[] args) {
FirstStatic.sendTo();
}
}
class FirstStatic extends BaseStatic {
public static String fname = "First";
public static String lname = "Static";
//public static void sendTo(){
// System.out.println("FirstStatic sendTo");
//}
}
You can do the following, of course, but the net effect is identical to the code shown above. If you need polymorphism, you'll need to do away with the statics--probably a good idea, anyway!
public class BaseStatic {
public static String fname = "Base";
public static String lname = "Static";
public static void send(){
System.out.println("BaseStatic send");
sendTo();
}
public static void sendTo(){
//How to call from here Child's static method.
System.out.println("BaseStatic sendTo");
}
public static void main(String[] args) {
FirstStatic.sendTo();
}
}
class FirstStatic extends BaseStatic {
public static String fname = "First";
public static String lname = "Static";
public static void sendTo(){
BaseStatic.sendTo();
}
}
EDIT: These examples are structured such that you can easily do the following to verify the behavior.
javac BaseStatic.java
java BaseStatic
Upvotes: 0
Reputation: 394126
There is no polymorphism for static methods. Therefore, in order to call a static method x
of class A
, you must write A.x()
.
FirstStatic.send()
will call BaseStatic
's send
only because FirstStatic
has no static send
method. However, BaseStatic
's send
will always call BaseStatic
's sendTo
, unless you explicitly call FirstStatic.sendTo()
.
Upvotes: 5