12, మార్చి 2012, సోమవారం

My classroom explanations on java inheritance on 12.mar.2012 single level and multilevel inheritance concepts and sample codes

//SINGLE LEVEL INHERITANCE
class base
{
int a,b;
base()
{
System.out.println("I AM AT BASE CLASS");
a=2;
b=3;

}
void add()
{
int sum=a+b;
System.out.println("the sum is" + sum);
}
void display()
{
System.out.println("the values of a and b are "+a+b);

}}

class derrived extends base
{
int c;
derrived()
{
System.out.println("I AM AT DERRIVED CLASS");
c=4;
}
void add()
{
int sum=a+b+c;
System.out.println("the sum is "+ sum);
}
void display()
{
System.out.println("the values of a and b are "+a+b+c);

}}


class single
{
public static void main(String args[])
{
base b=new base();
b.display();
b.add();
derrived d=new derrived();
d.display();
d.add();


}}


//implementation of multilevel inheritance in java
import java.io.*;
import java.lang.*;
class box
{
int length, breadth, height;

box()
{
 length=2;
 breadth=3;
 height=4;
}

//method-1 display the values on the screen
void display()
{
System.out.println("the values of box are "+length+"  , "+ breadth+ "  ,   "+height);
}
//method-2 calculation of the volume
void volume()
{
int volume;
volume=length* breadth* height;
System.out.println("the volume is"+volume);
}}


class wbox extends box
{
int weight;
wbox()
{
weight=3;
}

void wdis()
{
System.out.println("the weight  of box is"+ weight);
}}

class cwbox extends wbox
{
String color="green";
void cdisplay()
{
System.out.println("the color of box is"+ color);
}}


public class multilevel
{
public static void main(String args[]) throws Exception
{
//here we are calling methods on base class object 
box b=new box();
b.display();
b.volume();
System.out.println();
System.out.println();
//here we are calling methods on 1st level derrived class object 
wbox w=new wbox();
//w.weight=2; if we activate this instruction then in the wdisplay weight is =2 and in the colorbox is 3
w.display();
w.wdis();
w.volume();
System.out.println();
System.out.println();

//here we are calling methods on 2nd level derrived class object 
cwbox c=new cwbox();
c.cdisplay();
c.wdis();
c.display();
c.volume();
}}

కామెంట్‌లు లేవు:

కామెంట్‌ను పోస్ట్ చేయండి