java - Abstract class and dynamic binding -


so i've been studying abstract classes , dynamic binding , decided test out couple of examples.

i have following 3 classes: abstractdemo (main), myabstract , mysubabstract. main method calling methods both classes using dynamic or static binding.

all of following calls work except last 1 try use dynamic binding , call 1 of methods defined in subclass (sub1()). assume despite being declared reference of superclass object still able find method declared within object's class.

can 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 = 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();   } } 

myabstract h = new mysubabstract(); h.sub1();

this create , object mysubabstract , store in reference of type myabstract means can call methods myabstract unless cast ((mysubabstract) h).

see polymorphism exemple


Comments

Popular posts from this blog

angular - Is it possible to get native element for formControl? -

unity3d - Rotate an object to face an opposite direction -

javascript - Why jQuery Select box change event is now working? -