A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/java/output-of-java-program-set-4/ below:

Output of Java Program | Set 4

Output of Java Program | Set 4

Last Updated : 23 Jul, 2025

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++.



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4