Clarity with method overriding - java

Was curious about the correct definition of the overridden method and the overriding method.
In my understanding the overriding method is the method in the subclass that overrides the method with same signature and return type in the base class.
I have however seen sources refer to the overridden method as being the method in the subclass that overrides the method in the base class.
So which is the overridden method and which is the overriding method?
Sorry if this is a bit of a silly question

Let's assume we have a class SubClass extends SuperClass, then:
SuperClass#method <- overridden
^
|
overrides
|
SubClass#method <- overriding
Apart from that, wikipedia tells us:
The implementation in the subclass overrides (replaces) the implementation in the superclass by providing a method that has same name, same parameters or signature, and same return type as the method in the parent class.

class A {
public void method() {
System.out.println("I don't know if I am overriden, but I'm not overriding anything");
}
}
class B extends A {
public void method() {
System.out.println("I am overriding A.method() which has now been overriden");
}
}
You can also read the section of the JLS that describes overriding, implementing, hiding, overloading etc. for more in depth understanding.

A direct example from the Java Documentation :
public class Animal {
public static void testClassMethod() {
System.out.println("The class" + " method in Animal.");
}
public void testInstanceMethod() {
System.out.println("The instance " + " method in Animal.");
}
}
public class Cat extends Animal {
public static void testClassMethod() {
System.out.println("The class method" + " in Cat.");
}
public void testInstanceMethod() {
System.out.println("The instance method" + " in Cat.");
}
public static void main(String[] args) {
Cat myCat = new Cat();
Animal myAnimal = myCat;
Animal.testClassMethod();
myAnimal.testInstanceMethod();
}
}
The reason I used this example is, look at the scenario from your real-world situation. A Animal might have certain general features. But a Cat will have some features that are different from a generic Animal , but certain features that are an improvement over the generic Animal features. So, the Cat seems to override (will contain the overriding methods) the Animal features.
Another simple example if you are interested in cars. Say, there is a Car . It'll have an acceleration method. But a Ferrari will obviously have a better acceleration than a Car. But, a Ferrari is a Car. So, Ferrari overrides a method in Car. SO, overriding method is in subclass and the overriden method is in the base class.
So, do you get the point now? Overriding methods are present in the subclasses. But the methods that are overriden are present in the base class.

Related

How a program can know which method use (polymorphism)

I have two classes
First class named Myclass This is the parent class
public class Myclass {
public static int x = 10;
static void printX() {
System.out.println("From the Superclass x = " + x);
}
}
Second class named MySecondClass This the child class
public class MySecondClass extends Myclass {
static void printX() {
System.out.print("From the Subclass x = " + x);
}
public static void main(String[] args) {
printX();
}
}
As a newbie in Java Programming, I want to understand the Polymorphism; How can it choose between the two methods printX()? And in the code above why does it choose the MySecondClass method ?
Welcome to the community.
What you are trying to do here is called overriding. Although in reality java does not allow static methods to be overridden. If you instantiate the child class and call "printX" it will call the overridden method in the child class.
IE: From the Subclass x = .
But if you instantiate the parent class and call the method it will print "From the Superclass"
Although in this scenario what you are doing is not "overriding" as the methods are static. But this approach is called "method hiding"
To answer your question, it chose the second method because the second method (child class method) has hidden your super class method.
If methods are static, then it is determined at compile time which method is called, based on the class involved in the call.
If methods are instance members, then the relevant method body is looked up by its signature on the instance's concrete class, at runtime, falling back progressively upward on super classes until found. Consider that a simple map of signature-to-functionpointer, in each class and super classes, if you prefer.

What is significance of the term " hiding " in the method hiding concept in java? [duplicate]

This question already has answers here:
What is method hiding in Java? Even the JavaDoc explanation is confusing
(8 answers)
When is method hiding practically used?
(5 answers)
Closed 4 years ago.
The question has been put up to discuss around the term hiding which is associated with static methods in java.
Whenever a static method with the same signature is defined in the parent and the child class, the child class method is said to have hidden the method in the parent class. My question is around the usage of hiding, as we know static methods would be accessed by the class name or if we try to create a reference (which is a bad practice), method would be called based on the reference type. So how does hiding comes into picture, take example of below code:
public class Animal {
public static void testClassMethod() {
System.out.println("The static method in Animal");
}
}
public class Cat extends Animal {
public static void testClassMethod() {
System.out.println("The static method in Cat");
}
public static void main(String[] args) {
Cat myCat = new Cat();
Animal myAnimal = myCat;
Animal.testClassMethod(); // prints The static method in Animal
}
}
Can someone please explain how child method has hidden the parent method here? (parent method is being called using parent reference, so how does hiding comes into picture)
This demonstrates exactly why it's a bad practice to intend to hide a static method. The method is chosen statically, at compile time, without any consideration for the actual instance type.
I suppose the take home phrase should be "hiding is not overriding... and don't do it", to mean that Java doesn't even look at the object/instance (only looking at the declared type):
Cat myCat = new Cat();
Animal myAnimal = myCat;
Animal.testClassMethod();
myAnimal.testClassMethod(); //bad to do, but you can see it uses the declared "Animal" class
Cat.testClassMethod(); //Uses method in Cat
myCat.testClassMethod(); //Uses method in Cat
((Animal) null).testClassMethod(); //Uses Animal method, doesn't look at instance
((Cat) null).testClassMethod(); //Uses Cat method, doesn't look at instance
Now the interesting part: what if you remove the method from Cat?
All of these invocations will still work, using the Animal method, which means that:
It's a very bad practice to hide static methods
It's equally bad to use class instances to invoke static methods, because in the case of hidden methods, it's easy to be misled...
To answer the question: hiding is illustrated with Cat.testClassMethod() or myCat.testClassMethod(), which invokes the static method based on the declared type. When there's no testClassMethod() in Cat, Java calls the parent's.
How has the child method hidden the parent method here?
As you said, by defining a static method with the identical signature.
How does hiding comes into the picture?
Cat.testClassMethod();
Some may expect the invocation of the parent method here (by analogy with polymorphism). But the idea of hiding by class methods is different:
If a class C declares or inherits a static method m, then m is said to hide any method m', where the signature of m is a subsignature (§8.4.2) of the signature of m', in the superclasses and superinterfaces of C that would otherwise be accessible (§6.6) to code in C.
...
A hidden method can be accessed by using a qualified name or by using a method invocation expression (§15.12) that contains the keyword super or a cast to a superclass type.
...
class Super {
static String greeting() { return "Goodnight"; }
String name() { return "Richard"; }
}
class Sub extends Super {
static String greeting() { return "Hello"; }
String name() { return "Dick"; }
}
class Test {
public static void main(String[] args) {
Super s = new Sub();
System.out.println(s.greeting() + ", " + s.name()); // Goodnight, Dick
}
}
JLS 10 - 8.4.8.2. Hiding (by Class Methods)
This example is perfect to show the difference between overriding and hiding. At the same time, it is a bad practice demonstration - calling static methods on an instance.
I will try to make it clear by providing another example.
Since public static methods are inherited, the following snippet
class Animal {
public static void testClassMethod() {
System.out.println("The static method in Animal");
}
}
class Cat extends Animal {
public static void main(String[] args) {
// Cat: I don't have own method, probably I inherited it from the parent.
// O, yes. I can call it.
Cat.testClassMethod();
}
}
prints
The static method in Animal
Now we're going to add testClassMethod to Cat.
class Animal {
public static void testClassMethod() {
System.out.println("The static method in Animal");
}
}
class Cat extends Animal {
public static void testClassMethod() {
System.out.println("The static method in Cat");
}
public static void main(String[] args) {
// Cat: I have two version of the method: mine and the inherited one.
// The caller specified my class name, so he wanted my version.
// I will call my method hiding the parent method.
Cat.testClassMethod();
// If he wanted Animal's version, he would write
Animal.testClassMethod();
// or (DON'T DO THIS)
((Animal)new Cat()).testClassMethod();
}
}
All final, static and private methods and variables use static binding and are bonded by compiler. Static binding uses Type information for binding (in this case Animal).
So, in your case myAnimal.testClassMethod(); will print the static method in Animal because declared type is Animal.
static methods don't take part in dynamic binding (polymorphism).
static methods aren't overritten, static methods are hidden by the subclass.
someone who calls Cat.testClassMethod() might expect the behaviour of Animal.testClassMethod()
So Cat.testClassMethod() is hiding Animal.testClassMethod()

Can I override using subclass object as parameter in Java?

I have classes as follows
public class Useful
{
public void f(Object a)
{
System.out.println("In base f");
}
public void g(String a)
{
System.out.println("In base g");
}
}
public class MoreUseful extends Useful
{
public void f(String a)
{
System.out.println("In derived f");
}
public void g(Object a)
{
System.out.println("In derived g");
}
}
I am trying to override base class method but I am changing the parameters in derived class.
in method MoreUseful.f() I am using subclass parameter (String) as against Object in base class.
in method MoreUseful.g() I am using superclass parameter (Object) as against String in base class.
Is it possible to override these way?
Which of the above two cases will be correct overriding?
No, that's not possible, and would be a violation of the LSP.
By inheriting from a class, you express that your subclass MoreUseful is actually a Useful and therefore exposes all the functionality that Useful exposes. If you removed the ability to invoke f with an object, you'd break that promise.
You are free to overload f so that you have an f(String s) method though.
The g() method is indeed overriden. f(), however, is not overriden - it's overloaded. An easy way to verify this is to add #Override on each method you intend to override - if it results in a compilation error, you aren't overriding properly.

Is this still polymorphism?

While coding, I got an interesting doubt about polymorphism and I couldn't understand a solution for this.
public class Animal {
public void getLegs() {
SOP("4 legs");
}
}
public class Kangaroo extends Animal {
public void getLegs() {
SOP("2 legs");
}
public static void main(String[] args) {
Animal a = new Kangaroo(); // without changing this how can I get Animal getLegs
SOP(a.getLegs()); // Important Line
}
}
Now If I want to call the getLegs method of Animal, how do I? Is it possible? Is it still polymorphism?
Yes, it is the most basic form of demonstrating polymorphisim.
Basically you are dealing with an Animal named a. When you call a.getLegs() your code doesn't bind to the implementation of getLegs() in Animal, rather it binds to the lowest sub-class implementation, getLegs() in Kangraoo().
If the Animal has an implementation, it is said to be hidden by the subclass implementation. If Animal has no implementation, then it is not possible to construct stand-alone classes of Animal as they lack implementations for all of the required methods, and under such a circumstance, Animal is said to be an abstract class (one that cannot be constructed directly, but only can be constructed by it's sub classes).
If you really want to call your method for Animal, and you can employ a static method, you can use hiding instead of overriding.
It works as follows: for static methods only, the called method is the one related to the declared type, not the object instance. In other words, it follows the class because the method is a class method, not an instance method.
An example, adapted from this page:
public class Animal {
public static void testClassMethod() {
System.out.println("The class" + " method in Animal.");
}
public void testInstanceMethod() {
System.out.println("The instance " + " method in Animal.");
}
}
public class Kangaroo extends Animal {
public static void testClassMethod() {
System.out.println("The class method" + " in Kangaroo.");
}
public void testInstanceMethod() {
System.out.println("The instance method" + " in Kangaroo.");
}
public static void main(String[] args) {
Kangaroo myRoo = new Kangaroo();
Animal myAnimal = myRoo;
myRoo.testInstanceMethod();
myAnimal.testInstanceMethod();
Kangaroo.testClassMethod();
Animal.testClassMethod();
}
}
The result will be (pay attention to the 3rd and 4th lines, as opposed to the 1st and 2nd):
The instance method in Kangaroo.
The instance method in Kangaroo.
The class method in Kangaroo.
The class method in Animal.
In Java it's not possible to access Animal's implementation. It will always return Kangaroo's version.
(Note in C# it is possible by tagging the overriding method with "new", but it's a fairly specialised use case).
Accessing what appears to be an Animal but getting the behaviour specified by Kangaroo is exactly what polymorphism is - the ability for a child object to be substituted wherever its parent is expected.
In general you wouldn't want to have the calling code know about the inheritance hierarchy because this would tightly couple your code together. If you genuinely need to access Animal's implementation of this method it suggests your design is probably wrong.
The spirit of Polymorphism is to execute different code decided at runtime. To make it more clear, I'll modify your code a bit.
public class Animal {
public void getLegs(){
SOP('4 legs');
}
}
public class Kangaroo extends Animal{
public void getLegs(){
SOP('2 legs');
}
public static void main(String[] args){
Animal a = new Kangaroo(); //without changing this how can I get Animal getLegs
Kangaroo kng= new Kangaroo ();
Animal an = new Animal();
SOP(a.getLegs()); // Kangaroo's version is called
SOP(kng.getLegs()); //Again, Kangaroo's version is called
SOP(an.getLegs()); //Animal version is called
}
}
and Yes, as all say you can't call Animal from your line Animal a = new Kangaroo();..as none will want to do it. Rather he will directly write. Animal a = new Animal();..
So finally it is the object not referance which decides which method will be called
Now If I want to call the getLegs method of Animal, how do I? Is it possible?
If you want to access the overridden method - which contradicts polymorphism - you can use reflection. Get the getLegs method from Animal's class, and then invoke it on your Kangaroo object. However, this is a hack, and not something you'd do in a regular program.
SOP( Animal.class.getMethod("getLegs").invoke(a) );

Overriding vs Hiding Java - Confused

I'm confused on how overriding differs from hiding in Java. Can anyone provide more details on how these differ? I read the Java Tutorial but the sample code still left me confused.
To be more clear, I understand overriding well. My issue is that I don't see how hiding is any different, except for the fact that one is at the instance level while the other is at the class level.
Looking at the Java tutorial code:
public class Animal {
public static void testClassMethod() {
System.out.println("Class" + " method in Animal.");
}
public void testInstanceMethod() {
System.out.println("Instance " + " method in Animal.");
}
}
Then we have a subclass Cat:
public class Cat extends Animal {
public static void testClassMethod() {
System.out.println("The class method" + " in Cat.");
}
public void testInstanceMethod() {
System.out.println("The instance method" + " in Cat.");
}
public static void main(String[] args) {
Cat myCat = new Cat();
Animal myAnimal = myCat;
Animal.testClassMethod();
myAnimal.testInstanceMethod();
}
}
Then they say:
The output from this program is as follows:
Class method in Animal.
The instance method in Cat.
To me, the fact that calling a class method testClassMethod() directly from the Animal class executes the method in Animal class is pretty obvious, nothing special there. Then they call the testInstanceMethod() from a reference to myCat, so again pretty obvious that the method executed then is the one in the instance of Cat.
From what I see, the call hiding behaves just like overriding, so why make that distinction? If I run this code using the classes above:
Cat.testClassMethod();
I'll get:
The class method in Cat.
But if I remove the testClassMethod() from Cat, then I'll get:
The class method in Animal.
Which shows me that writing a static method, with the same signature as in the parent, in a subclass pretty much does an override.
Hopefully I'm making clear my where I'm confused and someone can shed some light. Thanks very much in advance!
Overriding basically supports late binding. Therefore, it's decided at run time which method will be called. It is for non-static methods.
Hiding is for all other members (static methods, instance members, static members). It is based on the early binding. More clearly, the method or member to be called or used is decided during compile time.
In your example, the first call, Animal.testClassMethod() is a call to a static method, hence it is pretty sure which method is going to be called.
In the second call, myAnimal.testInstanceMethod(), you call a non-static method. This is what you call run-time polymorphism. It is not decided until run time which method is to be called.
For further clarification, read Overriding Vs Hiding.
Static methods are hidden, non-static methods are overriden.
The difference is notable when calls are not qualified "something()" vs "this.something()".
I can't really seem to put it down on words, so here goes an example:
public class Animal {
public static void something() {
System.out.println("animal.something");
}
public void eat() {
System.out.println("animal.eat");
}
public Animal() {
// This will always call Animal.something(), since it can't be overriden, because it is static.
something();
// This will call the eat() defined in overriding classes.
eat();
}
}
public class Dog extends Animal {
public static void something() {
// This method merely hides Animal.something(), making it uncallable, but does not override it, or alter calls to it in any way.
System.out.println("dog.something");
}
public void eat() {
// This method overrides eat(), and will affect calls to eat()
System.out.println("dog.eat");
}
public Dog() {
super();
}
public static void main(String[] args) {
new Dog();
}
}
OUTPUT:
animal.something
dog.eat
This is the difference between overrides and hiding,
If both method in parent class and child class are an instance method, it called overrides.
If both method in parent class and child class are static method, it called hiding.
One method cant be static in parent and as an instance in the child. and visa versa.
If I understand your question properly then the answer is "you already are overriding".
"Which shows me that writing a static method, with the same name as in the parent, in a subclass pretty much does an override."
If you write a method in a subclass with exactly the same name as a method in a superclass it will override the superclass's method. The #Override annotation is not required to override a method. It does however make your code more readable and forces the compiler to check that you are actually overriding a method (and didn't misspell the subclass method for example).
Overriding happens only with instance methods.
When the type of the reference variable is Animal and the object is Cat then the instance method is called from Cat (this is overriding). For the same acat object the class method of Animal is used.
public static void main(String[] args) {
Animal acat = new Cat();
acat.testInstanceMethod();
acat.testClassMethod();
}
Output is:
The instance method in Cat.
Class method in Animal.
public class First {
public void Overriding(int i) { /* will be overridden in class Second */ }
public static void Hiding(int i) { /* will be hidden in class Second
because it's static */ }
}
public class Second extends First {
public void Overriding(int i) { /* overridden here */ }
public static void Hiding(int i) { /* hides method in class First
because it's static */ }
}
The rule for memorizing is simple: a method in an extending class
can't change static to void and
can't change void to static.
It will cause of compile-error.
But if void Name is changed to void Name it's Overriding.
And if static Name is changed to static Name it's Hiding. (Both the static method of the subclass as well as the one of the superclass can be called, depending on the type of the reference used to call the method.)
In this code snippet I use 'private' access modifier instead of 'static' to show you difference between hiding methods and overriding methods.
class Animal {
// Use 'static' or 'private' access modifiers to see how method hiding work.
private void testInstancePrivateMethod(String source) {
System.out.println("\tAnimal: instance Private method calling from "+source);
}
public void testInstanceMethodUsingPrivateMethodInside() {
System.out.println("\tAnimal: instance Public method with using of Private method.");
testInstancePrivateMethod( Animal.class.getSimpleName() );
}
// Use default, 'protected' or 'public' access modifiers to see how method overriding work.
protected void testInstanceProtectedMethod(String source) {
System.out.println("\tAnimal: instance Protected method calling from "+source);
}
public void testInstanceMethodUsingProtectedMethodInside() {
System.out.println("\tAnimal: instance Public method with using of Protected method.");
testInstanceProtectedMethod( Animal.class.getSimpleName() );
}
}
public class Cat extends Animal {
private void testInstancePrivateMethod(String source) {
System.out.println("Cat: instance Private method calling from " + source );
}
public void testInstanceMethodUsingPrivateMethodInside() {
System.out.println("Cat: instance Public method with using of Private method.");
testInstancePrivateMethod( Cat.class.getSimpleName());
System.out.println("Cat: and calling parent after:");
super.testInstanceMethodUsingPrivateMethodInside();
}
protected void testInstanceProtectedMethod(String source) {
System.out.println("Cat: instance Protected method calling from "+ source );
}
public void testInstanceMethodUsingProtectedMethodInside() {
System.out.println("Cat: instance Public method with using of Protected method.");
testInstanceProtectedMethod(Cat.class.getSimpleName());
System.out.println("Cat: and calling parent after:");
super.testInstanceMethodUsingProtectedMethodInside();
}
public static void main(String[] args) {
Cat myCat = new Cat();
System.out.println("----- Method hiding -------");
myCat.testInstanceMethodUsingPrivateMethodInside();
System.out.println("\n----- Method overriding -------");
myCat.testInstanceMethodUsingProtectedMethodInside();
}
}
Output:
----- Method hiding -------
Cat: instance Public method with using of Private method.
Cat: instance Private method calling from Cat
Cat: and calling parent after:
Animal: instance Public method with using of Private method.
Animal: instance Private method calling from Animal
----- Method overriding -------
Cat: instance Public method with using of Protected method.
Cat: instance Protected method calling from Cat
Cat: and calling parent after:
Animal: instance Public method with using of Protected method.
Cat: instance Protected method calling from Animal
I think this is not yet fully explained.
Please see the following example.
class Animal {
public static void testClassMethod() {
System.out.println("The static method in Animal");
}
public void testInstanceMethod() {
System.out.println("The instance method in Animal");
}
}
public class Cat extends Animal {
public static void testClassMethod() {
System.out.println("The static method in Cat");
}
public void testInstanceMethod() {
System.out.println("The instance method in Cat");
}
public static void main(String[] args) {
Animal myCat = new Cat();
Cat myCat2 = new Cat();
myCat.testClassMethod();
myCat2.testClassMethod();
myCat.testInstanceMethod();
myCat2.testInstanceMethod();
}
}
The output will be as follows.
The static method in Animal
The static method in Cat
The instance method in Cat
The instance method in Cat
Based on my recent Java studies
method overriding, when the subclass have the same method with the same signature in the subclass.
Method hiding, when the subclass have the same method name, but different parameter. In this case, you're not overriding the parent method, but hiding it.
Example from OCP Java 7 book, page 70-71:
public class Point {
private int xPos, yPos;
public Point(int x, int y) {
xPos = x;
yPos = y;
}
public boolean equals(Point other){
.... sexy code here ......
}
public static void main(String []args) {
Point p1 = new Point(10, 20);
Point p2 = new Point(50, 100);
Point p3 = new Point(10, 20);
System.out.println("p1 equals p2 is " + p1.equals(p2));
System.out.println("p1 equals p3 is " + p1.equals(p3));
//point's class equals method get invoked
}
}
but if we write the following main:
public static void main(String []args) {
Object p1 = new Point(10, 20);
Object p2 = new Point(50, 100);
Object p3 = new Point(10, 20);
System.out.println("p1 equals p2 is " + p1.equals(p2));
System.out.println("p1 equals p3 is " + p1.equals(p3));
//Object's class equals method get invoked
}
In the second main, we using the Object class as static type, so when we calling the equal method in Point object, it's waiting a Point class to arrive as a parameter,but Object coming. So the Object class equals method getting run, because we have an equals(Object o) there. In this case, the Point's class equals dosen't overrides, but hides the Object class equals method.
public class Parent {
public static void show(){
System.out.println("Parent");
}
}
public class Child extends Parent{
public static void show(){
System.out.println("Child");
}
}
public class Main {
public static void main(String[] args) {
Parent parent=new Child();
parent.show(); // it will call parent show method
}
}
// We can call static method by reference ( as shown above) or by using class name (Parent.show())
The linked java tutorial page explains the concept of overriding and hiding
An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.
If a subclass defines a static method with the same signature as a static method in the superclass, then the method in the subclass hides the one in the superclass.
The distinction between hiding a static method and overriding an instance method has important implications:
The version of the overridden instance method that gets invoked is the one in the subclass.
The version of the hidden static method that gets invoked depends on whether it is invoked from the superclass or the subclass.
Coming back to your example:
Animal myAnimal = myCat;
/* invokes static method on Animal, expected. */
Animal.testClassMethod();
/* invokes child class instance method (non-static - it's overriding) */
myAnimal.testInstanceMethod();
Above statement does not show hiding yet.
Now change the code as below to get different output:
Animal myAnimal = myCat;
/* Even though myAnimal is Cat, Animal class method is invoked instead of Cat method*/
myAnimal.testClassMethod();
/* invokes child class instance method (non-static - it's overriding) */
myAnimal.testInstanceMethod();
In addition to the examples listed above, here is a small sample code to clarify the distinction between hiding and overriding:
public class Parent {
// to be hidden (static)
public static String toBeHidden() {
return "Parent";
}
// to be overridden (non-static)
public String toBeOverridden() {
return "Parent";
}
public void printParent() {
System.out.println("to be hidden: " + toBeHidden());
System.out.println("to be overridden: " + toBeOverridden());
}
}
public class Child extends Parent {
public static String toBeHidden() {
return "Child";
}
public String toBeOverridden() {
return "Child";
}
public void printChild() {
System.out.println("to be hidden: " + toBeHidden());
System.out.println("to be overridden: " + toBeOverridden());
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
child.printParent();
child.printChild();
}
}
The call of child.printParent() outputs:
to be hidden: Parent
to be overridden: Child
The call of child.printChild() outputs:
to be hidden: Child
to be overridden: Child
As wee can see from the outputs above (especially the bold marked outputs), method hiding behaves differently from overriding.
Java allows both hiding and overriding only for methods. The same rule does not apply to variables. Overriding variables is not permitted, so variables can only be hidden (no difference between static or non-static variable). The example below shows how the method getName() is overriden and the variable name is hidden:
public class Main {
public static void main(String[] args) {
Parent p = new Child();
System.out.println(p.name); // prints Parent (since hiding)
System.out.println(p.getName()); // prints Child (since overriding)
}
}
class Parent {
String name = "Parent";
String getName() {
return name;
}
}
class Child extends Parent {
String name = "Child";
String getName() {
return name;
}
}
At runtime the child version of an overridden method is always executed for an instance
regardless of whether the method call is defi ned in a parent or child class method. In this
manner, the parent method is never used unless an explicit call to the parent method is
referenced, using the syntax
ParentClassName.method().
Alternatively, at runtime the parent
version of a hidden method is always executed if the call to the method is defined in the
parent class.
In method overriding, method resolution is done by the JVM on the basis of runtime object. Whereas in method hiding, method resolution is done by the compiler on the basis of reference.
Thus,
If the code would have been written as,
public static void main(String[] args) {
Animal myCat = new Cat();
myCat.testClassMethod();
}
The Output would be as below:
Class method in Animal.
It is called hiding because the compiler hides the super class method implementation, when subclass has the same static method.
Compiler has no restricted visibility for overridden methods and it’s only during runtime that it’s decided which one is used.
This is the difference between overriding and hiding:
Animal a = new Cat();
a.testClassMethod() will call the method in parent class since it is an example of method hiding. The method to be called is determined by the type of the reference variable and decided at compile time.
a.testInstanceMethod() will call the method in child class since it is an example of method overriding. The method to be called is determined by the object which is used to call the method at runtime.
How is static method hiding happening in java?
Cat class is extending Animal class. So in Cat class will have both static methods (i mean Child class's static method and Parent class's static method)
But how JVM hiding Parent static method? How it's dealing in Heap and Stack?

Categories

Resources