• Post Reply Bookmark Topic Watch Topic
  • New Topic

Don't understand output  RSS feed

 
Jyotish Pal
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Can anybody tell me the reason for the below output:
public class TestFoo {

/**
* @param args
*/
public static void main(String[] args) {

Child.show();

}

}

class Parent {

public static void show() {
System.out.println("I am in Parent!!");
}

}

class Child extends Parent {

}

The output is :I am in Parent!!
Can you please tell whats the reason for it?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch.

Why exactly do you not understand the output? What did you expect, and how is the actual result different from what you expect?

Child extends Parent, so it inherits the methods from class Parent. Since there's no show() method in class Child, the show() method in the superclass Parent is called instead.
 
Jyotish Pal
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Thanks for the reply.
The method show() is static and static methods cant be inherited.
So, how can it invoke the parent class method if the method is called on child class name?
 
Stefano Carniel
Greenhorn
Posts: 27
Android Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
all of the accessible methods (public and protected) are inherited. The difference is that static method with same signature are hidden, not overridden
 
Jyotish Pal
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi stefano,
Thanks a lot for the reply.So that means the static show() method also gets inherited to the child class and It can be accessed using the Child class(Child.show()) but we cant call it Overriding instead its hiding.But when we add the below method to child class which is not static and parent class contains the static show method then why does it cause a compilation issue?It would be better if you can explain this a bit more.
public void show() {
System.out.println("I am in child!!");
}
 
Stefano Carniel
Greenhorn
Posts: 27
Android Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the compiler itself gives you the answer. A static method can be overridden only by static method.

This example can clarify:



Usually calls to overridden methods are resolved at runtime, depending on the type of the object. Instead, call to static methods are resolved at compile time (and this makes sense since they can be invoked without instantiating an object).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!