java - Run Time Polymorphism -
class { public void display(){ system.out.println("from class a"); } } class b extends { public void display() { system.out.println("from class b"); } } public class test { public static void main(strings[] args){ a = new a(); b = new b() a.display(); b.display(); } } output:
from class class b now, getting output expected. want know why using a b = new b(), when same thing can achieve using b b = new b().
advantage of using former techniques, , when beneficial me?
lets take example here. know birds can fly, there exceptions. know behavior, lets model this.
generally, birds can fly, so:
class bird { void fly() { system.out.println("i can fly"); } } class eagle extends bird { void fly() { system.out.println("i can fly high"); } } we know ducks can't fly, don't birds. @ runtime whether specific bird can fly or not, depending on bird.
class duck extends bird { void fly() { system.out.println("i can walk or swim only"); } } class flightdemo { public static void main(string[] args) { bird bird = new bird(); bird.fly(); // output: can fly bird eagle = new eagle(); eagle.fly(); // output: can fly high bird duck = new duck(); duck.fly(); // output: can walk or swim } } you saw @ runtime it's decided ducks can't fly. can override fly behavior , walk or swim. saw duck bird, , can't fly, have overridden behavior, , still duck bird, , can walk or swim.
Comments
Post a Comment