Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
<pre lang="java">interface Superclass {
 
    void doSmth();
}
 
class Subclass implements Superclass {
 
    Subclass() {
        super();//line 1
    }
 
    @Override
    public void doSmth() {
        System.out.println("Do something");
    }
}

I learned from a book mentioning, "Interfaces do not have constructors". But if that's the case then why there isn't a run-time error, while adding super() in the subclass constructor? 


What I have tried:

<pre><pre lang="java"><pre>interface Superclass {
 
    void doSmth();
    //Superclass()
    //{}
}
 
class Subclass implements Superclass {
 
    Subclass() {
        super();
        System.out.println("oca.Subclass.<init>()");
    }
 
    @Override
    public void doSmth() {
        System.out.println("Do something");
    }
}
public class Q1
{
    public static void main(String[] args) {
        Superclass sc=new Subclass();//line 2
        Subclass sb=new Subclass();//line 3
    }
}

output
oca.Subclass.<init>()
oca.Subclass.<init>()


Also, I learned that whenever there is an instantiation of a subclass, then implicitly compiler will add super() in the subclass's default constructor which in turn invokes the parent class constructor. So in this case too why didn't it produce a runtime error even? 
Also, there's a compile-time error when I declare a constructor for the interface. 
Could anyone help me understand this ?
Posted
Updated 18-Aug-18 22:35pm

1 solution

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900