Open In App
Related Articles

Output of Java Program | Set 4

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report
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++.

Feeling lost in the vast world of Backend Development? It's time for a change! Join our Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:

  • Comprehensive Course
  • Expert Guidance for Efficient Learning
  • Hands-on Experience with Real-world Projects
  • Proven Track Record with 100,000+ Successful Geeks

Last Updated : 27 Sep, 2018
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads
Complete Tutorials