Mustapha Hadeed Mustapha Hadeed - 1 month ago 10
Java Question

why accessing a method specific to an object from a super reference fails?

Consider, for example, the following code

class Main {

public static void main(String[] args) {

Parent obj = new Child();

obj.firstMethod(); // Prints >> from child Class (polymorphism, great!)
obj.secondMethod(); // why this call fails?
// the obj variable reference a Child object
// which has secondMethod!


static class Parent {

Parent() {}

void firstMethod () {
System.out.println("from Parent Class");

static class Child extends Parent {

Child() {}

void firstMethod () {
System.out.println("from child Class");

void secondMethod () {

So obj variable is just a reference of type Parent, and the actual object the reference is pointing to is of type Child. I can't understand why such access fails!


The language spec answer: refer to JLS Sec 15.12. Emphasis added.

15.12.1. Compile-Time Step 1: Determine Class or Interface to Search

The first step in processing a method invocation at compile time is to figure out the name of the method to be invoked and which class or interface to search for definitions of methods of that name.


For the class or interface to search, there are six cases to consider, depending on the form that precedes the left parenthesis of the MethodInvocation:

  • ...
  • If the form is ExpressionName . [TypeArguments] Identifier, then the class or interface to search is the declared type T of the variable denoted by ExpressionName if T is a class or interface type, or the upper bound of T if T is a type variable.

15.12.2. Compile-Time Step 2: Determine Method Signature

The second step searches the type determined in the previous step for member methods.

In obj.secondMethod();, ExpressionName is obj, which has declared type Parent. As such, the declared type T is Parent, not Child, so only methods in Parent are searched for. There's no method in Parent called secondMethod, so it's a compile-time error.