Tuesday, April 24, 2018

What is the output of the program ? [based on method overriding]

  1. class SampleExec1 {
  2. void run() {
  3. System.out.println("SampleExec1 run");
  4. }
  5. }
  6. class SampleExec2 extends SampleExec1 {
  7. void run() {
  8. System.out.println("SampleExec2 run");
  9. }
  10. }
  11. public class SampleExecution {
  12. public static void main(String[] args) {
  13. SampleExec2 ex = new SampleExec1();
  14. ex.run();
  15. }
  16. }
Output: compile time error at line 13. Type mismatch: cannot convert from SampleExec1 to SampleExec2

--------------------------------------------------------------------
  1. class SampleExec1 {
  2. void run() {
  3. System.out.println("SampleExec1 run");
  4. }
  5. }
  6. class SampleExec2 extends SampleExec1 {
  7. void run() {
  8. System.out.println("SampleExec2 run");
  9. }
  10. }
  11. public class SampleExecution {
  12. public static void main(String[] args) {
  13. SampleExec2 ex = (SampleExec2 )new SampleExec1();
  14. ex.run();
  15. }
  16. }
Output: 
Exception in thread "main" java.lang.ClassCastException: SampleExec1 cannot be cast to SampleExec2 at SampleExecution.main(SampleExecution .java:14)

--------------------------------------------------------------------
  1. class SampleExec1 {
  2. void run() {
  3. System.out.println("SampleExec1 run");
  4. }
  5. }
  6. class SampleExec2 extends SampleExec1 {
  7. void run() {
  8. System.out.println("SampleExec2 run");
  9. }
  10. }
  11. public class SampleExecution {
  12. public static void main(String[] args) {
  13. SampleExec1 ex = new SampleExec2();
  14. ex.run();
  15. }
  16. }
Output: SampleExec2 run

No comments:

Post a Comment

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...