• Post Reply Bookmark Topic Watch Topic
  • New Topic

Question on Inheritance  RSS feed

 
Raji Chidam
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

Here is a code:

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.");
}
@SuppressWarnings("static-access")
public static void main(String[] args)
{
Animal myCat = (Animal) new Cat();
myCat.testClassMethod(); // This static method call using instance variable is not a good pratice. But just played around
myCat.testInstanceMethod();
}
}

public class Cat extends Animal
{
public static void testClassMethod()
{
System.out.println("The class method in Catssss.");
}

public void testInstanceMethod()
{
System.out.println("The instance method in Cat.");
}
}

This is the result:

The class method in Animal.
The instance method in Cat.

(Please note: First result is from Animal class while 2nd one is from Cat class.)

Can someone please explain why myCat.testClassMethod(); calles parents class static method?. Thank You
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please edit your message and put your code between code tags so it's easier to read.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static methods use the reference type, in this case Animal. The object itself is ignored. In fact, the following will also work:
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch
 
Raji Chidam
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Rob. Info was very interesting to know.
 
Muhammad Khojaye
Ranch Hand
Posts: 449
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Remember static method can be hidden but cannot override. Overriding uses polymorphism and invokes the correct method based on the actual type of the instance but in the case of static methods, we know that they do not require any underlying instance and they are linked to the class as a whole. Also see here.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!