Forums Register Login

The game of statics

+Pie Number of slices to send: Send
I read on all the forums so many times that Static methods cannot be inherited and cannot be overridden. But I came across the code which is allowing me to override and inherit static methods. Please go through the code below for overriding the static method.


package foo;

class A{

A(){
System.out.println("Here is A's constructor");
}

public static void print()
{
System.out.println("Printing A");
}

}

public class B extends A{

B(){
System.out.println("Here is B's constructor");
}

public static void print()
{
System.out.println("Printing B");
}


public static void main(String[] args){

B b = new B();

B.print();

A.print();

}
}

The output I got for this was allowing me to override this method print. It worked fine. Please let me know if it is really possible to override and inherit static method.
+Pie Number of slices to send: Send
Hi Harshad,

Originally posted by Harshad:I read on all the forums so many times that Static methods cannot be inherited and cannot be overridden. But I came across the code which is allowing me to override and inherit static methods. Please go through the code below for overriding the static method.



Whar do you mean by inheritance ?

try this :
A a = new B();
a.print();
you will know it by yourself !
+Pie Number of slices to send: Send
That example doesn't demonstrate overriding.

Static methods can be inherited by subclasses.

However, you cannot override them.
+Pie Number of slices to send: Send
Hi Keith,

I just want Harsad to know the fact that "overriding will not take place by that code."

You got me wrong. So sad.
+Pie Number of slices to send: Send
Sorry Srinivasan. My post was a comment to the OP, not a criticism of your post.
+Pie Number of slices to send: Send
Harshaut Raut, welcome to the Ranch.

Posted by Srinivasan thoyyeti

try this :
A a = new B();
a.print();

Now try thisYou have two separate methods in different classes, which just happen to have the same name.

Try this:-Result: won't work. You are not overriding at all.
You would be much easier to understand if you took that bucket off of your head. And that goes for the tiny ad too!
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 968 times.
Similar Threads
Contructor "good or bad"
Polymorphic behavior provided by inheritance programming assignment
abstract
Question on overriding
Static Methods in an Interface
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 03:58:38.