Skip to content
Related Articles

Related Articles

Improve Article

Output of Java Program | Set 4

  • Difficulty Level : Medium
  • Last Updated : 27 Sep, 2018

Predict the output of following Java Programs:

Question 1

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

Output: Compiler Error
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.

Question 2

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

Output: Compiler Error in line “Complex c1 = new Complex();”
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++.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :