TechTurtle
TechTurtle

Reputation: 29

Abstract class and dynamic binding

So I've been studying abstract classes and dynamic binding and decided to test out a couple of examples.

I have the following 3 classes: AbstractDemo (main), MyAbstract and MySubAbstract. The main method is calling methods from both classes using dynamic or static binding.

All of the following calls work except for the last one where I try to use dynamic binding and call one of the methods defined only in the subclass (sub1()). I would assume that despite being declared with a reference of the superclass the object would still be able to find a method declared within that object's class.

Can someone please explain why?

public abstract class MyAbstract {
 public abstract void abs1();   
 public abstract void abs2();

 public void nonAbs1() {
    System.out.println("MyAbstract nonAbs1");
 }

 public void nonAbs2() {
    System.out.println("MyAbstract nonAbs2");
 }
}


public class MySubAbstract extends MyAbstract {

 public void abs1() {
     System.out.println("MySubAbstract abs1()"); 
 }

 public void abs2() {
     System.out.println("MySubAbstract abs2()");
 }

 public void sub1() {
      System.out.println("MySubAbstract sub1()");
 }

 public void sub2() {
      System.out.println("MySubAbstract sub2()");
 }

 public void nonAbs1() {
      System.out.println("MySubAbstract nonAbs1()");
 }
}


public class AbstractDemo {

 public static void main(String[] args) {
    MySubAbstract a = new MySubAbstract(); a.abs1();
    MySubAbstract b = new MySubAbstract(); b.sub1();
    MySubAbstract c = new MySubAbstract(); c.nonAbs2();
    MySubAbstract d = new MySubAbstract(); d.nonAbs1();
    MySubAbstract e = new MySubAbstract(); e.nonAbs2(); 
    MyAbstract f = new MySubAbstract(); f.abs1();
    MyAbstract g = new MySubAbstract(); g.nonAbs1();
    MyAbstract h = new MySubAbstract(); h.sub1();
  }
}

Upvotes: 0

Views: 2827

Answers (2)

Simon PA
Simon PA

Reputation: 746

MyAbstract h = new MySubAbstract(); h.sub1();

This will create and object MySubAbstract and store it in a reference of type MyAbstract which means you can only call methods from MyAbstract unless you cast it ((MySubAbstract) h).

see polymorphism as exemple

Upvotes: 1

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26926

From your code h is declared as MyAbstract, so without an explicit casting you can access only methods declared in MyAbstract (both abstract and concrete methods).

To call sub1() you need to cast it

MyAbstract h = new MySubAbstract(); 
((MySubAbstract) h).sub1();

Upvotes: 2

Related Questions