Static method override - java

class XYZ{
public static void show(){
System.out.println("inside XYZ");
}
}
public class StaticTest extends XYZ {
public static void show() {
System.out.println("inside statictest");
}
public static void main(String args[]){
StaticTest st =new StaticTest();
StaticTest.show();
}
}
though we know static methods cant be overridden. Then what actually is happening?

Static methods belong to the class. They can't be overridden. However, if a method of the same signature as a parent class static method is defined in a child class, it hides the parent class method. StaticTest.show() is hiding the XYZ.show() method and so StaticTest.show() is the method that gets executed in the main method in the code.

Its not overriding they are two different method in two different class with same signature. but method from XYZ isn't available in child class through inheritance .
It will call method from StaticTest

It's not overriden properly said... Static methods are 'tied' to the class so
StaticTest.show();
and
XYZ.show();
are two totally different things. Note you can't invoke super.show()

To see the difference you have to use more powerful example:
class Super {
public static void hidden(Super superObject) {
System.out.println("Super-hidden");
superObject.overriden();
}
public void overriden() {
System.out.println("Super-overriden");
}
}
class Sub extends Super {
public static void hidden(Super superObject) {
System.out.println("Sub-hidden");
superObject.overriden();
}
public void overriden() {
System.out.println("Sub-overriden");
}
}
public class Test {
public static void main(String[] args) {
Super superObject = new Sub();
superObject.hidden(superObject);
}
}
As Samit G. already have written static methods with same signature in both base and derived classes hide the implementation and this is no-overriding. You can play a bit with the example by changing the one or the another of the static methods to non-static or changing them both to non-static to see what are the compile-errors which the java compiler rises.

It's not an override, but a separate method that hides the method in XYZ.

So as I know, any static member (method or state) is an attribute of a class, and would not be associated with any instance of a class. So in your example, XYZ is a class, and so is StaticTest (as you know). So by calling the constructor two things first happen. An Object of type Class is created. It has a member on it call showed(). Class, XYZ.class, extends from Object so has all those Object methods on it plus show(). Same with the StaticClass, the class object has show() on it as well. They both extend java.lang.Object though. An instance of StaticClass would also be an instance of XYZ. However now the more interesting question would be what happens when you call show() on st?
StaticClass st = new StaticClass();
st.show();
XYZ xyz = st;
xyz.show();
What happens there? My guess is that it is StaticClass.show() the first time and XYZ.show() the second.

Static methods are tied to classes and not instances (objects).
Hence the invocations are always ClassName.staticMethod();
When such a case of same static method in a subclass appears, its called as refining (redefining) the static method and not overriding.

// Java allows a static method to be called from an Instance/Object reference
// which is not the case in other pure OOP languages like C# Dot net.
// which causes this confusion.
// Technically, A static method is always tied to a Class and not instance.
// In other words, the binding is at compile-time for static functions. - Early Binding
//
// eg.
class BaseClass
{
public static void f1()
{
System.out.println("BaseClass::f1()...");
} // End of f1().
}
public class SubClass extends BaseClass
{
public static void f1()
{
System.out.println("SubClass::f1()...");
// super.f1(); // non-static variable super cannot be referenced from a static context
} // End of f1().
public static void main(String[] args)
{
f1();
SubClass obj1 = new SubClass();
obj1.f1();
BaseClass b1 = obj1;
b1.f1();
} // End of main().
} // End of class.
// Output:
// SubClass::f1()...
// SubClass::f1()...
// BaseClass::f1()...
//
//
// So even though in this case, called with an instance b1 which is actually referring to
// an object of type SuperClass, it calls the BaseClass:f1 method.
//

Related

#Override on static methods? [duplicate]

I'd like to know:
Why can't static methods be overridden in Java?
Can static methods be overloaded in Java?
Static methods can not be overridden in the exact sense of the word, but they can hide parent static methods
In practice it means that the compiler will decide which method to execute at the compile time, and not at the runtime, as it does with overridden instance methods.
For a neat example have a look here.
And this is java documentation explaining the difference between overriding instance methods and hiding class (static) methods.
Overriding: Overriding in Java simply means that the particular method would be called based on the run time type of the object and
not on the compile time type of it (which is the case with overriden
static methods)
Hiding: Parent class methods that are static are not part of a child class (although they are accessible), so there is no question of
overriding it. Even if you add another static method in a subclass,
identical to the one in its parent class, this subclass static method
is unique and distinct from the static method in its parent class.
Static methods can not be overridden because there is nothing to override, as they would be two different methods. For example
static class Class1 {
public static int Method1(){
return 0;
}
}
static class Class2 extends Class1 {
public static int Method1(){
return 1;
}
}
public static class Main {
public static void main(String[] args){
//Must explicitly chose Method1 from Class1 or Class2
Class1.Method1();
Class2.Method1();
}
}
And yes static methods can be overloaded just like any other method.
Static methods cannot be overridden because they are not dispatched on the object instance at runtime. The compiler decides which method gets called.
This is why you get a compiler warning when you write
MyClass myObject = new MyClass();
myObject.myStaticMethod();
// should be written as
MyClass.myStaticMethod()
// because it is not dispatched on myObject
myObject = new MySubClass();
myObject.myStaticMethod();
// still calls the static method in MyClass, NOT in MySubClass
Static methods can be overloaded (meaning that you can have the same method name for several methods as long as they have different parameter types).
Integer.parseInt("10");
Integer.parseInt("AA", 16);
Parent class methods that are static are not part of a child class (although they are accessible), so there is no question of overriding it. Even if you add another static method in a subclass, identical to the one in its parent class, this subclass static method is unique and distinct from the static method in its parent class.
Static methods can not be overridden because they are not part of the object's state. Rather, they belongs to the class (i.e they are class methods). It is ok to overload static (and final) methods.
Overloading is also called static binding, so as soon as the word static is used it means a static method cannot show run-time polymorphism.
We cannot override a static method but presence of different implementations of the same static method in a super class and its sub class is valid. Its just that the derived class will hide the implementations of the base class.
For static methods, the method call depends on the type of reference and not which object is being referred, i.e. Static method belongs only to a class and not its instances , so the method call is decided at the compile time itself.
Whereas in case of method overloading static methods can be overloaded iff they have diff number or types of parameters. If two methods have the same name and the same parameter list then they cannot be defined different only by using the 'static' keyword.
If I m calling the method by using SubClass name MysubClass then subclass method display what it means static method can be overridden or not
class MyClass {
static void myStaticMethod() {
System.out.println("Im in sta1");
}
}
class MySubClass extends MyClass {
static void myStaticMethod() {
System.out.println("Im in sta123");
}
}
public class My {
public static void main(String arg[]) {
MyClass myObject = new MyClass();
myObject.myStaticMethod();
// should be written as
MyClass.myStaticMethod();
// calling from subclass name
MySubClass.myStaticMethod();
myObject = new MySubClass();
myObject.myStaticMethod();
// still calls the static method in MyClass, NOT in MySubClass
}
}
No,Static methods can't be overriden as it is part of a class rather than an object.
But one can overload static method.
Static methods are a method whose single copy is shared by all the objects of the class. A static method belongs to the class rather than objects. since static methods are not dependent on the objects, Java Compiler need not wait till the creation of the objects so to call a static method we use syntax like ClassName.method() ;
In the case of method overloading, methods should be in the same class to overload.even if they are declared as static it is possible to overload them as,
Class Sample
{
static int calculate(int a,int b,int c)
{
int res = a+b+c;
return res;
}
static int calculate(int a,int b)
{
int res = a*b;
return res;
}
}
class Test
{
public static void main(String []args)
{
int res = Sample.calculate(10,20,30);
}
}
But in the case of method overriding, the method in the super class and the method in the sub class act as a different method. the super class will have its own copy and the sub class will have its own copy so it does not come under method overriding.
class SuperType {
public static void classMethod(){
System.out.println("Super type class method");
}
public void instancemethod(){
System.out.println("Super Type instance method");
}
}
public class SubType extends SuperType{
public static void classMethod(){
System.out.println("Sub type class method");
}
public void instancemethod(){
System.out.println("Sub Type instance method");
}
public static void main(String args[]){
SubType s=new SubType();
SuperType su=s;
SuperType.classMethod();// Prints.....Super type class method
su.classMethod(); //Prints.....Super type class method
SubType.classMethod(); //Prints.....Sub type class method
}
}
This example for static method overriding
Note: if we call a static method with object reference, then reference type(class) static method will be called, not object class static method.
Static method belongs to class only.
static methods are class level methods.
Hiding concept is used for static methods.
See : http://www.coderanch.com/how-to/java/OverridingVsHiding
The very purpose of using the static method is to access the method of a class without creating an instance for it.It will make no sense if we override that method since they will be accessed by classname.method()
No, you cannot override a static method. The static resolves against the class, not the instance.
public class Parent {
public static String getCName() {
return "I am the parent";
}
}
public class Child extends Parent {
public static String getCName() {
return "I am the child";
}
}
Each class has a static method getCName(). When you call on the Class name it behaves as you would expect and each returns the expected value.
#Test
public void testGetCNameOnClass() {
assertThat(Parent.getCName(), is("I am the parent"));
assertThat(Child.getCName(), is("I am the child"));
}
No surprises in this unit test. But this is not overriding.This declaring something that has a name collision.
If we try to reach the static from an instance of the class (not a good practice), then it really shows:
private Parent cp = new Child();
`enter code here`
assertThat(cp.getCName(), is("I am the parent"));
Even though cp is a Child, the static is resolved through the declared type, Parent, instead of the actual type of the object. For non-statics, this is resolved correctly because a non-static method can override a method of its parent.
You can overload a static method but you can't override a static method. Actually you can rewrite a static method in subclasses but this is not called a override because override should be related to polymorphism and dynamic binding. The static method belongs to the class so has nothing to do with those concepts. The rewrite of static method is more like a shadowing.
I design a code of static method overriding.I think It is override easily.Please clear me how its unable to override static members.Here is my code-
class Class1 {
public static int Method1(){
System.out.println("true");
return 0;
}
}
class Class2 extends Class1 {
public static int Method1(){
System.out.println("false");
return 1;
}
}
public class Mai {
public static void main(String[] args){
Class2 c=new Class2();
//Must explicitly chose Method1 from Class1 or Class2
//Class1.Method1();
c.Method1();
}
}
It’s actually pretty simple to understand – Everything that is marked static belongs to the class only, for example static method cannot be inherited in the sub class because they belong to the class in which they have been declared. Refer static keyword.
The best answer i found of this question is:
http://www.geeksforgeeks.org/can-we-overload-or-override-static-methods-in-java/
As any static method is part of class not instance so it is not possible to override static method
From Why doesn't Java allow overriding of static methods?
Overriding depends on having an instance of a class. The point of polymorphism is that you can subclass a class and the objects implementing those subclasses will have different behaviors for the same methods defined in the superclass (and overridden in the subclasses). A static method is not associated with any instance of a class so the concept is not applicable.
There were two considerations driving Java's design that impacted this. One was a concern with performance: there had been a lot of criticism of Smalltalk about it being too slow (garbage collection and polymorphic calls being part of that) and Java's creators were determined to avoid that. Another was the decision that the target audience for Java was C++ developers. Making static methods work the way they do have the benefit of familiarity for C++ programmers and were also very fast because there's no need to wait until runtime to figure out which method to call.
Definitely, we cannot override static methods in Java.
Because JVM resolves correct overridden method based upon the object at run-time by using dynamic binding in Java.
However, the static method in Java is associated with Class rather than the object and resolved and bonded during compile time.

Why doesn't the compiler complain when I try to override a static method?

I know that we cannot override static methods in Java, but can someone explain the following code?
class A {
public static void a() {
System.out.println("A.a()");
}
}
class B extends A {
public static void a() {
System.out.println("B.a()");
}
}
How was I able to override method a() in class B?
You didn't override anything here. To see for yourself, Try putting #Override annotation before public static void a() in class B and Java will throw an error.
You just defined a function in class B called a(), which is distinct (no relation whatsoever) from the function a() in class A.
But Because B.a() has the same name as a function in the parent class, it hides A.a() [As pointed by Eng. Fouad]. At runtime, the compiler uses the actual class of the declared reference to determine which method to run. For example,
B b = new B();
b.a() //prints B.a()
A a = (A)b;
a.a() //print A.a(). Uses the declared reference's class to find the method.
You cannot override static methods in Java. Remember static methods and fields are associated with the class, not with the objects. (Although, in some languages like Smalltalk, this is possible).
I found some good answers here: Why doesn't Java allow overriding of static methods?
That's called hiding a method, as stated in the Java tutorial Overriding and Hiding Methods:
If a subclass defines a class method with the same signature as a
class method in the superclass, the method in the subclass hides the
one in the superclass.
static methods are not inherited so its B's separate copy of method
static are related to class not the state of Object
You didn't override the method a(), because static methods are not inherited. If you had put #Override, you would have seen an error.
A.java:10: error: method does not override or implement a method from a supertype
#Override
^
1 error
But that doesn't stop you from defining static methods with the same signature in both classes.
Also, the choice of method to call depends on the declared type of the variable.
B b = null;
b.a(); // (1) prints B.a()
A a = new B();
a.a(); // (2) prints a.a()
At (1), if the system cared about the identity of b, it would throw a NPE. and at (2), the value of a is ignored. Since a is declared as an A, A.a() is called.
Your method is not overridden method. you just try to put #Override annotation before your method in derived class. it will give you a compile time error. so java will not allow you to override static method.
While goblinjuice answer was accepted, I thought the example code could improved:
public class StaticTest {
public static void main(String[] args) {
A.print();
B.print();
System.out.println("-");
A a = new A();
B b = new B();
a.print();
b.print();
System.out.println("-");
A c = b;
c.print();
}
}
class A {
public static void print() {
System.out.println("A");
}
}
class B extends A {
public static void print() {
System.out.println("B");
}
}
Produces:
A
B
-
A
B
-
A
If B had overridden print() it would have write B on the final line.
Static methods will called by its Class name so we don't need to create class object we just cal it with class name so we can't override static
for example
class AClass{
public static void test(){
}
}
class BClass extends AClass{
public static void test(){}
}
class CClass extends BClass{
public static void main(String args[]){
AClass aclass=new AClass();
aclass.test(); // its wrong because static method is called
// by its class name it can't accept object
}
}
we just call it
AClass.test();
means static class can't be overridden
if it's overridden then how to cal it .
Static members belong to class not to any objects. Therefore static methods cannot be overriden. Also overiding happens at run time therefore compiler will not complain.
Howeve, you can add #Override annotation to method. This will flag compiler error.

What is method hiding in Java? Even the JavaDoc explanation is confusing

Javadoc says:
the version of the hidden method that gets invoked is the one in the superclass, and the version of the overridden method that gets invoked is the one in the subclass.
doesn't ring a bell to me. Any clear example showing the meaning of this will be highly appreciated.
public class Animal {
public static void foo() {
System.out.println("Animal");
}
}
public class Cat extends Animal {
public static void foo() { // hides Animal.foo()
System.out.println("Cat");
}
}
Here, Cat.foo() is said to hide Animal.foo(). Hiding does not work like overriding, because static methods are not polymorphic. So the following will happen:
Animal.foo(); // prints Animal
Cat.foo(); // prints Cat
Animal a = new Animal();
Animal b = new Cat();
Cat c = new Cat();
Animal d = null;
a.foo(); // should not be done. Prints Animal because the declared type of a is Animal
b.foo(); // should not be done. Prints Animal because the declared type of b is Animal
c.foo(); // should not be done. Prints Cat because the declared type of c is Cat
d.foo(); // should not be done. Prints Animal because the declared type of d is Animal
Calling static methods on instances rather than classes is a very bad practice, and should never be done.
Compare this with instance methods, which are polymorphic and are thus overridden. The method called depends on the concrete, runtime type of the object:
public class Animal {
public void foo() {
System.out.println("Animal");
}
}
public class Cat extends Animal {
public void foo() { // overrides Animal.foo()
System.out.println("Cat");
}
}
Then the following will happen:
Animal a = new Animal();
Animal b = new Cat();
Cat c = new Cat();
Animal d = null;
a.foo(); // prints Animal
b.foo(); // prints Cat
c.foo(); // prints Cat
d.foo(): // throws NullPointerException
First of all What is meant by method Hiding?
Method hiding means subclass has defined a class method with the same signature as a class method in the superclass. In that case the method of superclass is hidden by the subclass. It signifies that : The version of a method that is executed will NOT be determined by the object that is used to invoke it. In fact it will be determined by the type of reference variable used to invoke the method.
What is meant by method overriding?
Method overriding means subclass had defined an instance method with the same signature and return type( including covariant type) as the instance method in superclass. In that case method of superclass is overridden(replaced) by the subclass. It signifies that: The version of method that is executed will be determined by the object that is used to invoke it. It will not be determined by the type of reference variable used to invoke the method.
Why can't static methods be overridden?
Because, static methods are resolved statically (i.e. at compile time) based on the class they are called on and not dynamically as in the case with instance methods which are resolved polymorphically based on the runtime type of the object.
How should static methods be accessed?
Static methods should be accessed in static way. i.e. by the name of class itself rather than using an instance.
Here is the short Demo for method overriding and hiding:
class Super
{
public static void foo(){System.out.println("I am foo in Super");}
public void bar(){System.out.println("I am bar in Super");}
}
class Child extends Super
{
public static void foo(){System.out.println("I am foo in Child");}//Hiding
public void bar(){System.out.println("I am bar in Child");}//Overriding
public static void main(String[] args)
{
Super sup = new Child();//Child object is reference by the variable of type Super
Child child = new Child();//Child object is referenced by the variable of type Child
sup.foo();//It will call the method of Super.
child.foo();//It will call the method of Child.
sup.bar();//It will call the method of Child.
child.bar();//It will call the method of Child again.
}
}
Output is
I am foo in Super
I am foo in Child
I am bar in Child
I am bar in Child
Clearly, as specified, since foo is the class method so the version of foo invoked will be determined by the type of reference variable (i.e Super or Child) referencing the object of Child. If it is referenced by Super variable then foo of Super is called. And if it is referenced by Child variable then foo of Child is called.
Whereas,
Since bar is the instance method so the version of bar invoked is solely determined by the object(i.e Child) that is used to invoke it. No matter via which reference variable (Super or Child) it is called , the method which is going to be called is always of Child.
To overwrite a method means that whenever the method is called on an object of the derived class, the new implementation will be called.
To hide a method means that an unqualified call to that name in the scope of this class (i.e. in the body of any of its methods, or when qualified with the name of this class) will now call a completely different function, requiring a qualification to access the static method of the same name from the parent class.
More description Java Inheritance: Overwritten or hidden methods
If a subclass defines a class method with the same signature as a class method in the superclass, the method in the subclass hides the one in the superclass.
Hidden methods are in Static context, I believe. Static methods are not overridden, per se, because the resolution of method calls done by the compiler at the compile time itself. So, if you define a static method in the base class with the same signature as that one present in the parent class, then the method in the subclass hides the method inherited from super class.
class Foo {
public static void method() {
System.out.println("in Foo");
}
}
class Bar extends Foo {
public static void method() {
System.out.println("in Bar");
}
}
For example you can override instance methods in a super class but not static.
Hiding is Parent class has a static method named Foo and the sub class also has a static method called Foo.
Another scenario is the parent has a static method named Cat and the sub class has an instance method named Cat. (static and instance with the same signature can't intermix).
public class Animal {
public static String getCat() { return "Cat"; }
public boolean isAnimal() { return true; }
}
public class Dog extends Animal {
// Method hiding
public static String getCat() { }
// Not method hiding
#Override
public boolean isAnimal() { return false; }
}
class P
{
public static void m1()
{
System.out.println("Parent");
}
}
class C extends P
{
public static void m1()
{
System.out.println("Child");
}
}
class Test{
public static void main(String args[])
{
Parent p=new Parent();//Parent
Child c=new Child(); //Child
Parent p=new Child(); //Parent
}
}
If the both parent and child class method are static the compiler is responsible for method resolution based on reference type
class Parent
{
public void m1()
{
System.out.println("Parent");
}}
class Child extends Parent
{
public void m1()
{
System.out.println("Child")
}
}
class Test
{
public static void main(String args[])
{
Parent p=new Parent(); //Parent
Child c=new Child(); //Child
Parent p=new Child(); //Child
}
}
If both method are not static jvm is responsible for method resolution based on run time object
When super/parent class and sub/child class contains same static method including same parameters and signature. The method in the super class will be hidden by the method in sub class. This is known as method hiding.
Example:1
class Demo{
public static void staticMethod() {
System.out.println("super class - staticMethod");
}
}
public class Sample extends Demo {
public static void main(String args[] ) {
Sample.staticMethod(); // super class - staticMethod
}
}
Example:2 - Method Hiding
class Demo{
public static void staticMethod() {
System.out.println("super class - staticMethod");
}
}
public class Sample extends Demo {
public static void staticMethod() {
System.out.println("sub class - staticMethod");
}
public static void main(String args[] ) {
Sample.staticMethod(); // sub class - staticMethod
}
}
first of all always class a static method using class name.
if function is static then it is method hiding whereas function is non static then method is overriding.

Can a private method in super class be overridden in the sub-class?

Can private methods be overridden in Java?
If no, then how does the following code work?
class Base{
private void func(){
System.out.println("In Base Class func method !!");
};
}
class Derived extends Base{
public void func(){ // Is this a Method Overriding..????
System.out.println("In Derived Class func method");
}
}
class InheritDemo{
public static void main(String [] args){
Derived d = new Derived();
d.func();
}
}
No, you are not overriding it. You can check by trying to mark it with #Override, or by trying to make a call to super.func();. Both won't work; they throw compiler errors.
Furthermore, check this out:
class Base {
private void func(){
System.out.println("In base func method");
};
public void func2() {
System.out.println("func2");
func();
}
}
class Derived extends Base {
public void func(){ // Is this an overriding method?
System.out.println("In Derived Class func method");
}
}
class InheritDemo {
public static void main(String [] args) {
Derived D = new Derived();
D.func2();
}
}
It will print:
func2
In base func method
When you change func() in Base to public, then it will be an override, and the output will change to:
func2
In Derived Class func method
No, a private method cannot be overridden because the subclass doesn't inherit its parent's private members. You have declared a new method for your subclass that has no relation to the superclass method. One way to look at it is to ask yourself whether it would be legal to write super.func() in the Derived class. There is no way an overriding method would be banned from accessing the method it is overriding, but this would precisely be the case here.
No, it is not. You can mark an override just to make sure like this:
#Override
public void func(){
System.out.println("In Derived Class func method");
}
And in this case it would be a compiler error.
You are not overriding. You cannot override private members, you are merely defining a new method in Derived. Derived has no knowledge Base's implementation of func() since its declared as private. You won't get a compiler error when you define func() in Derived but that is because Derived does not know Base has an implementation of func(). To be clear: it would be incorrect to say you are overriding Base's implementation of func().
In addition to the already correct answer, consider this:
public class Private {
static class A {
public void doStuff() {
System.out.println(getStuff());
}
private String getStuff() {
return "A";
}
}
static class B extends A {
public String getStuff() {
return "B";
}
}
public static void main(String[] args) {
A a = new A();
a.doStuff();
a = new B();
a.doStuff();
B b = new B();
b.doStuff();
}
}
This will print
A
A
A
although B "overrides" getStuff(). As implementation of doStuff() is fixed to calling A#getStuff(), no polymorphism will be triggered.
Nope because if you do something like Base b = new Derived(); you still won't be able to call b.func(). What you're doing is called "hiding".
Since the method is private it is not visible to the other classes.Hence the derived class does not inherit this method.
So this is not the case of overriding
Method hiding will be happening here instead of overriding. like what happens in case of static.
Actually,you are not overriding.Before Java5
an overridden method's return type must match with parent class's method.
But Java 5 introduced a new facility called covariant return type.You can override a method with the same signature but returns a subclass of the object returned. In another words, a method in a subclass can return an object whose type is a subclass of the type returned by the method with the same signature in the superclass.
you can follow this thread :Can overridden methods differ in return type?
The private member of the base class cannot be access by anyone outside of the class and cannot be overridden. The function in the derive class is an independent function that can be access by anywhere.
The code would run the function in the derived class
A private method can never be over ridden. It is always hidden.
In your example - Derived class has one parent class private method and has its own function func. Both are different, and the func is not over ridden. Its a separate independent function.
If you create a new function in parent class calling parent class function, the parent func will be called, if parent class reference is used as opposed in the case of method over ridding
Note : An object defines the members which it has, and a reference defines which it can access
// Method Over ridding case
class Base{
public void func(){
System.out.println("Parent class");
};
public void func1(){
func();
}
}
class Derived extends Base{
public void func(){
System.out.println("Derived class");
}
}
class InheritDemo{
public static void main(String [] args){
Derived d = new Derived();
d.func1(); // Prints Derived class
Base b = new Derived();
b.func1(); // Prints Derived class - no matter parent reference is calling,as there as method is overridden - Check func1() is in parent class, but id doesn't call parent class func() as the compiler finds a func() method over ridden in derived class
}
}
// Method Hidding case - Private and static methods case
class Base{
private void func(){
System.out.println("Parent class");
};
public void func1(){
func()
}
}
class Derived extends Base{
public void func(){ // Is this a Method Overriding..????
System.out.println("Derived class");
}
}
class InheritDemo{
public static void main(String [] args){
Derived d = new Derived();
d.func1(); // Prints Derived class
Base b = new Derived();
b.func1();
// Prints Parent class - the reason is we are using the parent class reference, so compiler is looking for func() and it founds that there is one private class method which is available and is not over ridden, so it will call it. Caution - this won't happen if called using derived class reference.
b.func();
// this prints the Derived class - the compiler is looking func(), as Derived class has only one func() that it is implementing, so it will call that function.
}
}
Read comments in the below code snippet to find the answer.
Sources:
Definition reference:
Credits for the source code example(reference) from the book - "OCA Oracle Certified Associate Java SE 8 Programmer Study Guide Exam 1Z0-808 Book" from 'Jeanne Boyarsky' and 'Scott Selikoff'.
public class Deer {
public Deer() { System.out.print("Deer"); }
public Deer(int age) { System.out.print("DeerAge"); }
private boolean hasHorns() { return false; }
public static void main(String[] args) {
Deer deer = new Reindeer(5);
System.out.println(","+deer.hasHorns());// false is printed.
}
}
class Reindeer extends Deer {
public Reindeer(int age) { System.out.print("Reindeer"); }
private boolean hasHorns() { return true; } // Overriding possible, but is of no use in the below context.
// Below code is added by me for illustration purpose
public static void main(String[] args) {
Deer deer = new Reindeer(5);
//Below line gives compilation error.
//System.out.println(","+deer.hasHorns());
}
}

Is it possible to override a static method in derived class?

I have a static method defined in a base class, I want to override this method in its child class, is it possible?
I tried this but it did not work as I expected. When I created an instance of class B and invoke its callMe() method, the static foo() method in class A is invoked.
public abstract class A {
public static void foo() {
System.out.println("I am base class");
}
public void callMe() {
foo();
}
}
Public class B {
public static void foo() {
System.out.println("I am child class");
}
}
Static method calls are resolved on compile time (no dynamic dispatch).
class main {
public static void main(String args[]) {
A a = new B();
B b = new B();
a.foo();
b.foo();
a.callMe();
b.callMe();
}
}
abstract class A {
public static void foo() {
System.out.println("I am superclass");
}
public void callMe() {
foo(); //no late binding here; always calls A.foo()
}
}
class B extends A {
public static void foo() {
System.out.println("I am subclass");
}
}
gives
I am superclass
I am subclass
I am superclass
I am superclass
In Java, static method lookups are determined at compile time and cannot adapt to subclasses which are loaded after compilation.
Just to add a why to this. Normally when you call a method the object the method belongs to is used to find the appropriate implementation. You get the ability to override a method by having an object provide it's own method instead of using the one provided by the parent.
In the case of static methods there is no object to use to tell you which implementation to use. That means that the compiler can only use the declared type to pick the implementation of the method to call.
No. It's not possible.
Some similar (not the same) questions here and here.
Static Methods are resolved at compile time.So if you would like to call parent class method then you should explicitly call with className or instance as below.
A.foo();
or
A a = new A();
a.foo();
In a nutshell static method overriding is not polymorphism it is "method hiding".
When you override a static method you will have no access to the base class method as it will be hidden by the derived class..
Usage of super() will throw a compile time error..

Categories

Resources