Exercise - 5 (Inheritance)
a). Write a JAVA program to implement Single Inheritanceimport java.util.Scanner;
class Add
{
protected int a,b,sum;
void add()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter two values");
a=s.nextInt();
b=s.nextInt();
sum=a+b;
System.out.println("The sum of the given numbers is:"+sum);
}
}
class Mul extends Add
{
int mul;
void mul()
{
mul=a*b;
System.out.println("The product of the given numbers is:"+mul);
}
}
class Calculation
{
public static void main(String args[])
{
Mul m=new Mul();
m.add();
m.mul();
}
}
b). Write a JAVA program to implement multi level Inheritance
import java.util.Scanner;
class calculator
{
public static void main(String args[])
{
System.out.println("Enter the values:");
Scanner s=new Scanner(System.in);
int a=s.nextInt();
int b=s.nextInt();
Product pr=new Product();
pr.Addition(a,b);
pr.Substraction();
pr.Mul();
}
}
class Add
{
protected int p,q;
public void Addition(int x,int y)
{
p=x;
q=y;
int r=p+q;
System.out.println("Inside of the class 'Addition' ......");
System.out.println("The sum is:"+r);
}
}
class Sub extends Add
{
int diff;
public void Substraction()
{
int diff=p-q;
System.out.println("Inside of the class Sub.........");
System.out.println("Difference is:"+diff);
}
}
class Product extends Sub
{
int prod;
public void Mul()
{
int prod=p*q;
System.out.println("Inside of the class Product.......");
System.out.println("Product is:"+prod);
}
}
c). Write a java program for abstract class to find areas of different shapes
import java.util.Scanner;
abstract class Areas
{
public void display()
{
System.out.println("Inside of the abstract class....");
}
abstract void area();
}
class Rectangle extends Areas
{
int base=10;
int height=20;
public void area()
{
int area=base*height;
System.out.println("Area of the rectangle is:"+area);
}
}
class Square extends Areas
{
int base=15;
public void area()
{
int area1=base*base;
System.out.println("Area of the Square is:"+area1);
}
}
class Triangle extends Areas
{
int base=5;
int height=15;
public void area()
{
int area2=(base*height)/2;
System.out.println("Area of the Triangle is:"+area2);
}
}
class Geometry
{
public static void main(String args[])
{
Rectangle r=new Rectangle();
Square s=new Square();
Triangle t=new Triangle();
r.display();
r.area();
s.area();
t.area();
}
}
No comments:
Post a Comment