Wednesday, 5 November 2014

Method Overriding with Constructors

In method Overriding If sub class having default constructor then must super class having default constructor otherwise we will get exception. To avoid these problem means we can't write the default constructor in super class then we can write the sub class super() method by passing argument.

 class Main
{
Main(){
System.out.println("i am from super class");
}
Main(int a){
System.out.println("i am from super constructor class");
}

public void m1()
{
System.out.println("i am from Main class");
}
}
public class Meth_ovr extends Main{
Meth_ovr(){
//super(9); If not write the super class constructor
System.out.println("i am from sub contructor");
}

public void m1()
{
System.out.println("i am from sub class");
}
public void m2()
{
System.out.println("i am from m2 class");
}
public static void main(String[] args) {

Meth_ovr m=new Meth_ovr();
m.m1();
//Main mr= new Main();
//mr1.m1();
Main mr1= new Main();
mr1.m1();
}

}

No comments:

Post a Comment