import java.io.*;
class A
{
int i,j;
void showij(){
System.out.println("i ana j:"+i+""+j);
}
}
class B extends A{
int k;
void showk(){
System.out.println("k:"+k);
}
void sum()
{
System.out.println("i+j+k:"+(i+j+k));
}
}
class SimpleInheritance
{
public static void main(String args[])
{
A superOb=new A();
B subOb=new B();
superOb.i=10;
superOb.j=20;
System.out.println("Contents of superOb:");
superOb.showij();
System.out.println();
subOb.i=7;
subOb.j=8;
subOb.k=9;
System.out.println("Contents of subOb:");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum ofi,j and k in subOb:");
subOb.sum();
}
}
Member Access and Inheritance in java…
Example : Access
import java.io.*;
class A{
int i;
private int j;
void setij(int x,int y)
{
i=x;
j=y;
}
}
class B extends A
{
int total;
void sum()
{
total= i+j;
}
}
class Access
{
public static void main(String args[])
{
B subOb=new B();
subOb.setij(10,12);
subOb.sum();
System.out.println("Total is "+subOb.total);
}
}
Using super to Call Superclass constructors…
Example : Inherit1
import java.lang.*;
import java .io.*;
class book
{
int bno;
String bname;
double price;
public book(int n,String bn,double p)
{
bno=n;
bname=bn;
price=p;
}
void display()
{
System.out.println("\nBook Number="+bno);
System.out.println("\nBook Name="+bname);
System.out.println("\nBook Price="+price);
}
}
class purchase extends book
{
int qord;
double netcost;
public purchase(int n1,String bn1,double p1,int q)
{
super(n1,bn1,p1);
qord=q;
}
void display()
{
netcost=qord*super.price;
super.display();
System.out.println("\nQuanity ordered="+qord);
System.out.println("\nNet cost="+netcost);
}
}
class Inherit1
{
public static void main(String args[])
{
purchase pur=new purchase(10,"Black Book of java",500.00,34);
pur.display();
}
}
Method Overriding
Example : FindAreas
import java.io.*;
class Figure
{
double dim1;
double dim2;
Figure(double a,double b){
dim1 =a;
dim2 =b;
}
double area()
{
System.out.println("Area for Figure is undefined.");
return 0;
}
}
class Rectangle extends Figure
{
Rectangle (double a,double b)
{
super(a,b);
}
double area()
{
System.out.println("Inside Area for Rectangle.");
return dim1*dim2;
}
}
class Triangle extends Figure
{
Triangle(double a,double b)
{
super (a,b);
}
double area()
{
System.out.println("Inside Area for Triangle.");
return dim1*dim2/2;
}
}
class FindAreas
{
public static void main(String args[])
{
Figure f=new Figure(10,10);
Rectangle r=new Rectangle(9,5);
Triangle t=new Triangle(10,8);
Figure figref;
figref=r;
System.out.println("Area is "+figref.area());
figref=t;
System.out.println("Area is"+figref.area());
figref=f;
System.out.println("Area is"+figref.area());
}
}