Open In App

Output of Java Program | Set 2

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Predict the output of the following Java programs. 

Question 1: 

Java




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);
    }
}


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 the 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 the 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:  

Java




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);
    }
}


Output: 

Compiler Error

In the above program, there are no access permission issues because the Point and Main are in the same package and protected members of a class can be accessed in other classes of the same package. The problem with the code is: there is no default constructor in Point. 

Like C++, if we write our own parameterized 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 parameterized 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.
 



Last Updated : 18 May, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads