What is Printed?

What is being printed for this code?

 class Alpha {

 public void print() { System.out.print("Alpha "); }

  }

  public class Beta extends Alpha {

 public void print() { System.out.print("Beta"); }

 public static void main(String[] args) {

     Alpha a = new Beta();

     Beta b = (Beta)a;

     a.print();

     b.print();

 }

  }
AlphaBeta BetaBeta AlphaAlpha BetaAlpha

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

1 solution

Sri Sudheer
Apr 8, 2015

Here 'a' is just a reference but actual object is of type Beta .so when we are calling a.print() the output will be Beta. Next in object creation of Beta we are typecasting in to Beta .So if you call b.print() the same which called previously wiil be executed and beta will be printed.

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...