Open In App

Output of Java Program | Set 4

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Predict the output of the following Java Programs.

1. What is the output of the following program?

Java
// file name: Main.java 
  class Base { 
    protected void foo() {} 
}  
class Derived extends Base { 
    void foo() {} 
}  
public class Main { 
    public static void main(String args[]) { 
        Derived d = new Derived(); 
        d.foo(); 
    } 
} 

Options:

a) Program compiles and prints nothing
b) Program compiles and runs successfully
c) Compiler Error
d) Runtime Exception

Answer: (c) Compiler Error

Explanation: foo() is protected in Base and default in Derived. Default access is more restrictive. When a derived class overrides a base class function, more restrictive access can’t be given to the overridden function. If we make foo() public, then the program works fine without any error. The behavior in C++ is different. C++ allows to give more restrictive access to derived class methods.


2. What is the output of the following program?

Java
// file name: Main.java 
  class Complex { 
    private double re, im;     
    public String toString() { 
        return "(" + re + " + " + im + "i)"; 
    } 
    Complex(Complex c) { 
        re = c.re; 
        im = c.im; 
    } 
} 
  
public class Main { 
    public static void main(String[] args) { 
        Complex c1 = new Complex(); 
        Complex c2 = new Complex(c1); 
        System.out.println(c2); 
    } 
} 

Options:

a) (0.0 + 0.0i)
b) Compilation successful, prints default values
c) Runtime Error
d) Compiler Error in line “Complex c1 = new Complex();”

Answer: (d) Compiler Error in line “Complex c1 = new Complex();”

Explanation: In Java, if we write our own copy constructor or parameterized constructor, then compiler doesn’t create the default constructor. This behavior is same as C++.



Next Article
Practice Tags :

Similar Reads