pavan agrawal
pavan agrawal

Reputation: 1

Default and parameterize constructore

I am calling parametrized constructor of super class then also it is throwing compile time error such as no default constructor Why? Because as per the program i m not calling default constructor at all.

class Sup
{
    public Sup(String s)
    { 
        System.out.println("super"); 
    } 
} 

class Sub extends Sup 
{ 
    public Sub() 
    { 
        System.out.println("sub class"); 
    } 

    public static void main(String arg[]) 
    {  
        Sup s2=new Sup("pavan"); 
    } 
}

Upvotes: 0

Views: 72

Answers (2)

Jesper Fyhr Knudsen
Jesper Fyhr Knudsen

Reputation: 7927

You need to define the super classes default constructor, because unless otherwise specified the base classes constructor will try to call the super class, in your case the super class doesn't have a parameterless constructor so you'll get a compile error.

class Sup
{
    public Sup(){}

    public Sup(String s)
    { 
        System.out.println("super"); 
    } 
} 

class Sub extends Sup 
{ 
    public Sub() 
    { 
        System.out.println("sub class"); 
    } 

    public static void main(String arg[]) 
    {  
        Sup s2=new Sup("pavan"); 
    } 
}

Or make a explicit call to the super classes constructor(s) using super() and in your case for the parametrized constructor super("some string")

class Sup
{
    public Sup(String s)
    { 
        System.out.println("super"); 
    } 
} 

class Sub extends Sup 
{ 
    public Sub() 
    { 
        super("some string");

        System.out.println("sub class"); 
    } 

    public static void main(String arg[]) 
    {  
        Sup s2=new Sup("pavan"); 
    } 
}

Upvotes: 2

Kamil
Kamil

Reputation: 431

Your Sub() constructor is calling default constructor (which is done implicitly if you don't call super() explictly or call another constructor in the same class in first line of your constructor) in Sup class which you did not provide. You should add a call to Sup(String s) in Sub() constructor or add default no-param constructor in your Sup class.

Upvotes: 1

Related Questions