Predict the output of following Java Programs:
Question 1
// 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(); } } |
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: 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); } } |
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 DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Output of Java Program | Set 8
- Output of Java program | Set 26
- Output of Java program | Set 27
- Output of Java Program | Set 6
- Output of Java Program | Set 7
- Output of Java program | Set 17
- Output of Java Program | Set 3
- Output of Java Program | Set 9
- Output of Java Program | Set 2
- Output of Java Program | Set 1
- Output of Java Program | Set 19
- Output of Java Program | Set 11
- Output of Java program | Set 5
- Output of Java program | Set 28
- Output of Java program | Set 16 (Threads)
- Output of Java program | Set 23 (Inheritance)
- Output of Java program | Set 15 (Inner Classes)
- Output of Java program | Set 22 (Overloading)
- Output of Java program | Set 25 (Polymorphism)
- Output of Java Program | Set 20 (Inheritance)

