How are this() and super() used with constructors?
this() is used to invoke a constructor of the same class.
super() is used to invoke a superclass constructor.
SuperThisDemo.java
class SuperClass
{
int p;
public SuperClass(){
System.out.println("Super Class");
}
public SuperClass(int a)
{ //this();
this(20,40);
System.out.println("Super Class with " + a);
}
public SuperClass(int a,int b)
{
System.out.println("Super Class with a and b " + a+ " "+b);
}
public void area(){
System.out.println("Super Class with area ");
}
public void disp(){
System.out.println("disp Super Class with p "+p);
}
}
class SubClass extends SuperClass{
public SubClass()
{
super(10); super.area(); super.p=20; super.disp();
System.out.println("Sub Class");
}
}
public class SuperThisDemo{
public static void main(String s[])
{
(new SubClass()).disp(); //OR
//SubClass a=new SubClass(); //a.disp();
}
}
Recent Comments