Tuesday, July 8, 2014

Super Keyword usages in java

Example 1:
import java.io.*;
//superkeyword can be used to call the base class ((paramerised))constructor as well as to use the data members/member functions of the base class from the derived class
class superkeyword2
{
public static void main(String[] args)
{
derived2 d3=new derived2();
d3.function();
}
}
class base
{
void basefun(int x)
{
System.out.println("baseclass function called");
}
}
class derived extends base
{
void derivedfun()
{
super.basefun(10);//calls base classs function
System.out.println("this is derived class method...");
}
}
class derived2 extends derived
{
void function()
{
System.out.println("this is derived2 class method...gona call base class method");
super.derivedfun();//calls derived class which is the baseclass of derived class
derivedfun();//this just calls function within this same class
}
void derivedfun()
{
super.basefun(10);//calls base classs function
System.out.println("this is derived 2222222 class method...");
}
}



Example 2:

import java.io.*;
//superkeyword can be used to call the base class ((paramerised))constructor as well as ro use the data members/member functions of the base class from the derived class
class superkeyword
{
public static void main(String[] args)
{
derived2 d=new derived2();//calls the default costructors....
derived2 d1=new derived2('a');//ths calls the paramerised constructor of the derived 2...parameterised constructor can also call the default constructor of the base class or manually we can also use super()->for default constructor of the base class.....super(..) for calling any other para constructors of the base class
}
}
class base
{
base()
{
System.out.println("The default constructor of the base class");
}
base(int x)
{
System.out.println("The parameterised constructor of the base class");
}
}
class derived1 extends base
{
derived1()
{
super(10);//this calls the parameterised constructor of the base class// if ths stmt was not found thn the default constuctor would hav got called.....
System.out.println("the default constructor of the derived class");
}
derived1(int x,int y)
{
System.out.println("the parameterised constructor of the derived class");
}
}
class derived2 extends derived1
{
derived2()
{
System.out.println("the default constructor of the derived2 class");
}
derived2(char a)
{
super(10,20);//this calls the parameterised constructor of the derived1 class// if ths stmt was not found thn the default constuctor would hav got called.....
System.out.println("the parameterised constructor of the derived2 class");
}
}




No comments:

Post a Comment