accessing super class methods from object reference (newbie)

527 Views Asked by At

suppose I have this class:

class B extends A
{
  @Override 
  void foo () { ... }
}

Now if I am given an object of class B can I explicitly invoke the foo method from class A? I tried downcasting the object i.e.,

B b = new B();
((A)b).foo();

but that doesn't seem to work.

So is there a way to accomplish what I would like to do in Java?

4

There are 4 best solutions below

0
On

Always method invocation will be on type of the object due to polymorphism.

In this case even though you down cast, object is of type B, so foo() method from Class B will be invoked.

This sun tutorial may help you.

0
On

In Java, all functions/methods are virtual by default. So, in an inheritance scenario, a method call on a subtype always invokes the version of that method in the subtype irrespective of the reference type being supertype/subtype, i.e

A a = new B();
a.foo();

B b = new B();
b.foo()

both will invoke the version of foo() in B only.

If you are someone coming from C++ where functions have to be explicitly declared virtual and this kind of behavior is observed only with pointers, the behavior of the same in java would need to be understood differently.

0
On
B b = new B();
((A)b).foo();

In the second line , you are using the reference of object 'b'. So any method you call on its reference will call the overridden method foo() of object 'b'. Thinking in terms of object references will help you clearly understand OOPS concepts of Java.

0
On

Its like this.....

- The Most specific version of the method for that class is called.

Eg:

public class A{

  public void go(){

      System.out.println("A");

    }

 }


class B extends A{

  public static void main(String[] args){
     B b = new B();
     b.go();
   }

  }

In the above class B, as the method go() is Not overridden, so the method from class A will be called.

Now if its something like below then, the class B method go() will be called.

class B extends A {

  public void go(){

      System.out.println("B");

    }

   public static void main(String[] args){
     B b = new B();
     b.go();
   }

}

In the above class " The Most specific version of go() method is called "