Output of Java Program | Set 2

Predict the output of following Java programs.

Question 1

filter_none

edit
close

play_arrow

link
brightness_4
code

package main;
  
class Base {
    public void Print() {
        System.out.println("Base");
    }         
}
  
class Derived extends Base {    
    public void Print() {
        System.out.println("Derived");
    }
}
  
class Main{
    public static void DoPrint( Base o ) {
        o.Print();   
    }
    public static void main(String[] args) {
        Base x = new Base();
        Base y = new Derived();
        Derived z = new Derived();
        DoPrint(x);
        DoPrint(y);
        DoPrint(z);
    }
}

chevron_right


Output:

Base
Derived
Derived

Predicting the first line of output is easy. We create an object of type Base and call DoPrint(). DoPrint calls the print function and we get the first line.

DoPrint(y) causes second line of output. Like C++, assigning a derived class reference to a base class reference is allowed in Java. Therefore, the expression Base y = new Derived() is a valid statement in Java. In DoPrint(), o starts referring to the same object as referred by y. Also, unlike C++, functions are virtual by default in Java. So, when we call o.print(), the print() method of Derived class is called due to run time polymorphism present by default in Java.



DoPrint(z) causes third line of output, we pass a reference of Derived type and the print() method of Derived class is called again. The point to note here is: unlike C++, object slicing doesn’t happen in Java. Because non-primitive types are always assigned by reference.






Question 2

filter_none

edit
close

play_arrow

link
brightness_4
code

package main;
  
// filename Main.java 
class Point {
    protected int x, y;
   
    public Point(int _x, int _y) {
        x = _x;
        y = _y;
    }
}
  
public class Main {
    public static void main(String args[]) {
      Point p = new Point();
      System.out.println("x = " + p.x + ", y = " + p.y);
    }    
}

chevron_right


Output:
Compiler Error
In the above program, there are no access permission issues because the Test and Main are in same package and protected members of a class can be accessed in other classes of same package. The problem with the code is: there is not default constructor in Point. Like C++, if we write our own parametrized constructor then Java compiler doesn’t create the default constructor. So there are following two changes to Point class that can fix the above program.
1) Remove the parametrized constructor.
2) Add a constructor without any parameter.
Java doesn’t support default arguments, so that is not an option.

Please write comments if you find any of the answers/explanations incorrect, or want to share more information about the topics discussed above.



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


4


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.