This question already has answers here:
Why doesn't Java allow overriding of static methods?
(22 answers)
Closed 6 years ago.
public class Base {
private static boolean goo = true;
protected static boolean foo() {
goo = !goo;
return goo;
}
public String bar = "Base:" + foo();
public static void main(String[] args) {
Base base = new Sub();
System.out.println("Base:"+ base.foo());
}
}
public class Sub extends Base {
public String bar = "Sub:" + foo();
protected static boolean foo() {
return false;
}
}
Why the output is "Base: true"? foo() seems to be an overriding method so dynamic type is Sub, than why the return output isn't "false", and also the field of Base has a string, shouldn't there be its output?
In java, you can not override the static methods, If you redefine that static method of super class method in sub class then it becomes method over-written(method hiding), not overriding.
In your example, you are invoking it with the super class ref(base) so the super class method only invoked not the sub class method. so the output is "Base: true"
If you change it with non static method then the sub class method will be executed.
Here the rule is: super class ref and sub class object will work for non static methods.
When you are dealing with the word "static" in terms of a method or a variable, it refers that the method or a variable belong to the "class" and not its object.
When there is no object, there is no overriding.
In your class Base, you declared the main() method, in which you wrote the following statements.
Base base = new Sub();
System.out.println("Base:"+ base.foo());
Now, the reference variable type is Base and the object type is Sub. Since foo() is a static method it belongs to the class of which the reference variable is declared (i.e. Base).
Therefore, foo method of class Base is called.
Method overriding is used to override the behaviour of an object for a subclass and is not applicable for static methods. There is no reason to support this feature for static methods. Moreover, you don't need to create an object to access a static method. You can simply refer it by its name[foo()] or use classname as a prefix[eg: Sub.foo()].
As far as why true is being returned in an output is concerned , this is because you have already used below statement in your class , which invokes foo() method
public String bar = "Base:" + foo();
Since goo is a static variable, only one instance of this variable is maintained for this class . And on execution of above statement , the value of goo changes to false(goo=!goo,goo initially being true).
Later on , when you use base.foo() , foo() of base class will be executed [As method overriding not applicable for static methods and Base class reference is being used] which again reverts the value of goo making it true.
Related
**Java code-MySuper class is the parent class and is extended by MySub class.I am creating the object MySub mySub = new MySub().I thought the output would be "y" but when I tried to run the code it was showing null as an output **
class MySuper {
String strl = "x";
public MySuper() {
myMethod();
}
void myMethod() {
System.out.print(strl);
}
}
class MySub extends MySuper {
String str2 = "y";
void myMethod() {
System.out.print(str2);
}
public static void main(String[] args) {
MySub mySub = new MySub();
}
}
The implicit constructor used by MySub looks like this:
class MySub extends MySuper {
String str2;
MySub() {
super();
str2 = "y";
}
// rest omitted for brevity
}
While inline field initialization is technically moved into the constructor, that's not necessarily important to know in and of itself. The important part is that the super constructor is invoked before the subclass's fields are initialized. So, when the super constructor invokes the myMethod() method, which is overridden by the subclass, the str2 field has not yet been assigned a non-default value. This results in your code printing out null.
And this is why you should avoid invoking overridable methods in a constructor.
This is due to Java dynamic method dispatch.
In your example. when you're instancing with the default constructor a MySub instance, this implicitly performs a call to the superclass' constructor. Within the superclass' constructor there is a call to myMethod() which is declared in MySuper and overridden in MySub.
Now, even if myMethod is being called from the superclass' constructor, which could fool us into thinking that the superclass' version of myMethod is being called, this is not what is actually happening.
The instance that is performing all these calls is still a MySub instance; therefore the myMethod implementation that is being invoked by Java is the closest implementation to MySub, i.e. the myMethod overridden by MySub.
So, if in this case the myMethod version that is being invoked in the superclass' constructor is the one overridden by MySub, why it's not printing str2 value? This is because, although method calls are dynamically dispatched, fields are statically dispatched. In Java, only methods can override their base class' methods. Child class' fields can only shadow base class' fields (with the same name). So Java already knows at compile time which fields are being used and only at run time which method implementations are being invoked. This means that when you're using a field in a child class, you can be sure that the one you're using is always the one you're referring to.
Getting back to your example, since myMethod is being invoked from the superclass' constructor, at this point we're still initializing the parent object, the child class' fields have not been initialized yet, they still contain their default values (the default value for references is null). So, in your dynamically dispatched myMethod we are printing the value of the statically dispatched str2 which is still at null because the child class initialization has not happened yet.
Minor Mistakes:
null output is coming because of extending the MySuper class and extending MySuper class is not required because the default class object can be created anywhere in a package without extending that.
You have not called the method myMethod() after creating the object mySub.That's why it is not printing the output as y.
Solution:
Try the code below, it is working smoothly.
class MySuper {
String strl = "x";
public MySuper() {
myMethod();
}
void myMethod() {
System.out.print(strl);
}
}
// class MySub extends MySuper {
class MySub {
String str2 = "y";
void myMethod() {
System.out.print(str2);
}
public static void main(String[] args) {
MySub mySub = new MySub();
// extra line added
mySub.myMethod();
MySuper ms=new MySuper();
}
}
Can anybody explain me what is the reason for a sub class object is incapable of holding a super class constructor?
class Alpha
{
String getType1()
{
return "alpha";
}
}
class Beta extends Alpha
{
String getType1()
{
return "beta";
}
String acc()
{
return "acc";
}
}
public static void main(String[] args)
{
Alpha a1=new Beta();
System.out.println(a1.getType1());
}
Here the output is "beta"; but object a1 doesnt have the visibility to acc()?
Nothing surprising here:
System.out.println(a1.getType1());
You are calling a method that is defined in the super class; and overridden in the a subclass. You create an instance of the subclass; and the method that gets executed ... is the overridden version.
The fact that Beta contains another method which is not at all used in your example anyway doesn't come into play here at all. And even if getType1() would be calling acc() - that would still work. That is the essence of of polymorphism!
And just to be precise: none of the methods you have in your classes is a constructor!
i just found the answer here we need to know that when we create beta() internally it will call all its super class default constructors hence the JVM knows that there is more than one existing class but when i declare and initialze like:
Alpha a1=new Beta();
eventhough the JVM knows that beta class is existing but your restricting your access of a1 by saying it is of the type Alpha class hence it cannot access your subclass methods.
When you create a object of child class making reference to its parent class as you did, you only have visible to those methods which belongs to the parent class. but if you want to call the child method using reference of parent class then you have to declare the body of the method in parent class which you have in child class. then it will be visible and this concept is called method overriding.
If you don't need to create the object of your super class then you can declare class as abstract and then you can simply put that method as abstract keyword shown as below.
abstract class Alpha
{
String getType1()
{
return "alpha";
}
abstract String acc();
}
class Beta extends Alpha
{
String getType1()
{
return "beta";
}
#Overriding
String acc()
{
return "acc";
}
}
public static void main(String[] args)
{
Alpha a1=new Beta();
System.out.println(a1.getType1());
}
Child classes are privileged to access to default constructor of parent class until unless you have restricted it with private access modifier.
Your cases is an example of method overloading. Actual call to overloaded method is resolved at run time. Which method will be called, depends on the concrete object not type of object. Here your reference is of type Alpha but the object is of Type Beta. So method getType1() here will print beta which is correct behavior.
I am confused by the behaviour of the static method when it is overridden in the subclass.
Below is the code:
public class SuperClass {
public static void staticMethod() {
System.out.println("SuperClass: inside staticMethod");
}
}
public class SubClass extends SuperClass {
//overriding the static method
public static void staticMethod() {
System.out.println("SubClass: inside staticMethod");
}
}
public class CheckClass {
public static void main(String[] args) {
SuperClass superClassWithSuperCons = new SuperClass();
SuperClass superClassWithSubCons = new SubClass();
SubClass subClassWithSubCons = new SubClass();
superClassWithSuperCons.staticMethod();
superClassWithSubCons.staticMethod();
subClassWithSubCons.staticMethod();
}
}
Below is the output which we are getting :
1) SuperClass: inside staticMethod
2) SuperClass: inside staticMethod
3) SubClass: inside staticMethod
Why static method of superclass gets called here in the second case?
If method is not static, then according to polymorphism, method of the subclass is called when subclass object is passed on runtime.
static method resolution is always based on the Reference type.
The code
superClassWithSuperCons.staticMethod();
superClassWithSubCons.staticMethod();
subClassWithSubCons.staticMethod();
is converted to this after compilation
SuperClass.staticMethod();
SuperClass.staticMethod();
SubClass.staticMethod();
Accroding to this it is the call to SuperClass method not the subclass method.So you are getting the output of SuperClass method.
A method declared static cannot be overridden but can be re-declared. That's the answer.
A static method is not associated with any instance of a class so the concept is not applicable. Try the same with not static and you'll see the difference.
Your question is duplicated actually:
Why doesn't Java allow overriding of static methods?
Interesting question. I'm not familiar with the underlying mechanisms, but it seems that for static methods, the declared type (in your middle example, SuperClass), not the actual type SubClass is considered for resolving the method call. It actually makes sense because you're not looking at the actual instance of an object when calling a static function.
Static methods are redefined not overridden...
If you try to override the static method then it will be treated as a non overridden method of the sub class.
Static methods will be called based on the type of the reference not the object created.
For more information visit the page.
http://javaunturnedtopics.blogspot.in/2016/07/static-methods-are-redefined-not.html
So I know that in Java when you have a static method you are supposed to call it with the format ClassName.method() rather than use the same structure as you would for instance methods, namely:
ClassName myObject = new ClassName();
myObject.method();
However, if you were to do it this way it would still be valid code and would work. Let's say I decide to do this where the method in question is static, and have the following setup:
public SuperClass {
public static int foo(int x) {
return x;
}
}
public SubClass extends SuperClass {
public static int foo(int x) { // Overriding foo() in SuperClass
return x + 1;
}
}
public MyDriver {
public static void main(String[] args) {
SuperClass myObject = new SubClass(); // Upcasting.
System.out.println(myObject.foo(5)); // This should polymorphically print 6
}
}
What prints out on the screen, however, is 5 rather than 6. Why?
Static methods apply only to the class they are defined in, and they cannot be overridden.
When you call myObject.foo(5), you are calling SuperClass.foo(5) in reality, because you declared myObject as a SuperClass, regardless of whether you instantiated it as one.
The proper way to call a static method is to call it directly from the class it is declared in, so if you wanted to call SubClass.foo(), you must call it from an explicitly declared SubClass instance (meaning no upcasting), or you need to call SubClass.foo() like so.
The simple answer is that calling static methods from instances evaluates to calling those same methods from the declared type with no instance rather than the instance type.
I am not certain of this, but I would not be surprised if when the code is compiled into byte-code, that the instance static method call would actually be compiled into a direct call to the declared type.
Edit: An upvote brought my attention back to this and I cleaned up the explanation to make it more clear and fix some negligible grammatical mistakes on my part. I hope this helps future readers.
Using instances of a class to call that class's static methods is something you should avoid, since it can cause confusion. If you need to call any method polymorphically, make it an instance method. You cannot polymorphically call a static method. The reason the SuperClass invocation is called is because that is the apparent class of myObject at compile-time. This effect can also be seen in the following scenario:
public void doSomething(SuperClass param) {
System.out.println("SuperClass");
}
public void doSomething(SubClass param) {
System.out.println("SubClass");
}
public void test() {
SuperClass myObject = new SubClass();
doSomething(myObject);
}
If test() is called, SuperClass will be printed.
Static methods don't depends on the instance, they belong to the class and only to the class, in fact if you have a static method you'll always access to one unique instance always.
myObject.foo(5)
is only a shortcut, what you really are doing is
SuperClass.foo(5)
Static methods are treated as global by the JVM, they are not bound to an object instance at all. By the way, you can only overload static methods, but you can not override. So check for "Oracle Documentation for Overriding and Hiding Documents".
Defining a Method with the Same Signature as a Superclass's Method:
-----------------------------------------Superclass Instance MethodSuperclass Static Method
Subclass Instance Method Overrides Generates a compile-time error
Subclass Static Method Generates a compile-time error Hides
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Can we override static method in Java?
We cannot override the static methods of the base class.
Actually I tried something like this:
// Base class
public class StaticExampleImpl {
protected String name="overriding";
public static void display(){
System.out.println("static method display : base class");
}
}
Then the derived class is as follows:
//derived class
public class StaticDemo extends StaticExampleImpl {
// cannot override the static methods...
//#Override
public static void display(){
System.out.println("child!!! static method display");
}
public static void main(String[] args) {
StaticDemo d=new StaticDemo();
d.display(); // derived class display is called rather than Base class.
}
}
So, when I uncomment the #Override method, it gives error as "Static methods cannot be overriden". But with commenting it works fine. So, when we create the Objects and call the static methods with the instances, those work fine. so what is the difference??
because static methods are not get inherited.
When you uncomment #Override it means you are trying to override the
static method which is not possible thats why you are getting an
error.
But when you comment //#Override it means you are declaring a new
method in child class.
Static methods does not belong to an instance of a class, it belongs to the actual class.
When you call d.display();, you are really calling the static method of the StaticDemo d reference's static method.
if you did :
StaticExampleImpl d2 = new StaticDemo();d2.display(), you will find that it calls the base class's display.
However, don't do this. It leads to confusing code, and is a bad way to implement inheritance poorly.
Overriding depends the an instance of a class. polymorphismis that you can subclass a class and the objects implementing those subclasses will have different behaviors for those method defined in the superclass (and overridden in the subclasses) .static methods does not belong to an instance of a class so the concept is not applicable.
Static methods cannot be inherited. If you want to call the 'base' class static method, you have to explicitely call StaticExampleImpl.display().
Static methods are bound to class they can't be inherited thats why you can't have base class static method in derived class.
If you are trying to override a static method, there is probably something wrong with your design.
OOP and Polymorphism allows you to do the following:
public class MyClass1 {
public String toString() { return "MyClass1 Instance"; }
}
public class MyClass2 extends MyClass1 {
#Override
public String toString() { return "MyClass1 Instance"; }
}
public void printSomething(MyClass1 myclass1){
System.out.println(myclass1);
}
Inside printSomething, the toString method which is going to be called is the one on the runtime type of myClass1: when you pass inside printSomething an instance of MyClass2, its compile-type will be MyClass1 but its runtime type will be MyClass2
It is clear that to use polymorphism you need objects instances, where the actual runtime type could different from the compile type. Static methods however do not belong to any object instance, but to the class. Why don't you explain us what you are trying to achieve?
The following code:
StaticExampleImpl one = new StaticExampleImpl();
StaticDemo two = new StaticDemo();
StaticExampleImpl three = two;
one.display();
two.display();
three.display();
Will yield the following output:
static method display : base class
child!!! static method display
static method display : base class
As you can see, the method does not get inherited. This is why they are called 'static methods': they are called statically, not dynamically, as instance methods would be. The compile-time type of the class is what matters when calling static methods, not the runtime type.
This is also why you shouldn't call static methods through object instances. Always call them like this:
StaticExampleImpl.display();
StaticDemo.display();
This completely takes away the confusion that might (will) come up when people expect inheritance to work for these methods.
any static block in java, may be static variables, methods are loaded when the class is loaded. You probably know about class loader in java. So thing is static block (methods, variables or anything is static) is loaded once. So you can’t actually override any static block.
Commenting #Override means that you are writing another static method in sub class, but not just overriding base class method.