The blog of Jafar Aliyev

Archive

Creation date:

Tricky Polymorphism

Look at the following example Java class:

public class Main {

  static class A {
     private String title = "Title of A";

     public String getTitle() {
       return title;
    }

    String go() {
       return getTitle();
    }
  }

  static class B extends A {
    private String title = "Title of B";

    public String getTitle() {
       return title;
    }
  }

  public static void main(String... args) {
     A a = new A();
     B b = new B();
     System.out.println(a.go());
     System.out.println(b.go());
  }
}

If you run this class you'll get

Title of A
Title of B

Method a.go() calls a.getTitle() and it's OK. Method b.go() calls inherited method go() of class A. method go() in this case calls the method getTitle() of class B.

But if you change modifier of method getTitle() in class A from public to private (highlighted with bold font) the result will

Title of A
Title of A

In this case despite of polymorphism go() method of class A will call it's private getTitle() method. Watch out of this tricky question if you are goung to apply for SCJP exam. You may see the similar questions in exam too. The private method can not be inherited. Therefore polymorphizm does not take place here and ancestor of class calls its own method.

Author: Jafar N.Aliyev (Jsoft)

Read also

Use instanceof carefully
Usage of 'instanceof' method in some situations will give you a compilation error

Wrapper objects

Static and instance initilization blocks

Overloading

Java access and nonaccess modifiers
Look at this cheat sheet for Java access and nonaccess modifiers

Implicit typecasting

Protected details

Interface methods are always public

Static methods can not be overriden
Here I explain, why static methods can not be overriden

Implicit typecasting

Java Tips

Variable hiding

Postfix operators

Pattern Matching

Default values

String equality

© Copyright

All articles in this site are written by Jafar N.Aliyev. Reproducing of any article must be followed by the author name and link to the site of origin(this site). This site also keeps the same rules relative to the articles of other authors.