0% found this document useful (0 votes)
168 views

Write A Program To Demonstrate Use of Implementing Interfaces

The document describes an example Java program that implements interfaces. It defines an Area interface with a compute method and two classes, Rectangle and Circle, that implement the Area interface and provide an implementation of the compute method for calculating their respective areas. The main method creates instances of Rectangle and Circle, assigns them to an Area reference variable, and calls the compute method to calculate and print their areas. This demonstrates how interfaces can be used to achieve polymorphism in Java.

Uploaded by

nithya elysium
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
168 views

Write A Program To Demonstrate Use of Implementing Interfaces

The document describes an example Java program that implements interfaces. It defines an Area interface with a compute method and two classes, Rectangle and Circle, that implement the Area interface and provide an implementation of the compute method for calculating their respective areas. The main method creates instances of Rectangle and Circle, assigns them to an Area reference variable, and calls the compute method to calculate and print their areas. This demonstrates how interfaces can be used to achieve polymorphism in Java.

Uploaded by

nithya elysium
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 14

WRITE A PROGRAM TO DEMONSTRATE USE OF IMPLEMENTING

INTERFACES.
import java.lang.*;
interface Area
{
final static float pi=3.14F;
float compute(float x,float y);
}
class rectangle implements Area
{
public float compute(float x,float y)
{
return(pi*x*y);
}
}
class circle implements Area
{
public float compute(float x,float y)
{
return(pi*x*x);
}
}
class interfacedemo
{
public static void main(String a[])
{
rectangle rect=new rectangle();
circle cir=new circle();
Area A;
A=rect;
System.out.println("Area of rectangle="+A.compute(10,20));
A=cir;
System.out.println("Area of circle="+A.compute(30,0));
}
}

Abstract Classes and Abstract Methods

Program (Shape.java)
/**
* The Shape class is an abstract class that holds
* general data about a shape.
*/

public abstract class Shape


{
private double height; // To hold height.
private double width; //To hold width or base

// Set height and width


public void setValues(double height, double width)
{
this.height = height;
this.width = width;
}

//Get height
public double getHeight()
{
return height;
}

//Get width
public double getWidth()
{
return width;
}

// The getArea method is abstract.


// It must be overridden in a subclass.

public abstract double getArea();


}
Program (Rectangle.java)
/**
* This class Rectangle calculates
* the area of rectangle
*/

public class Rectangle extends Shape


{
//Calculate and return area of rectangle
public double getArea()
{
return getHeight() * getWidth();
}
}
Program (Triangle.java)
/**
* This class Triangle calculates
* the area of triangle
*/
public class Triangle extends Shape
{
//Calculate and return area of triangle
public double getArea()
{
return (getHeight() * getWidth()) / 2;
}
}
rogram(AbstractDemo.java)

/**
* This program demonstrates polymorphic behavior.
*/

public class AbstractDemo


{
public static void main(String[] args)
{
Shape shape;

// assign subclass reference to subclass variable


Rectangle rect = new Rectangle();

// shape points to the object rect.


shape = rect;

// Set data in Rectangle's object


shape.setValues(78, 5);

//Display the area of rectangle


System.out.println("Area of rectangle : " + shape.getArea());

// assign subclass reference to subclass variable


Triangle tri = new Triangle();

// shape points to the object rect.


shape = tri;

// Set data in Triangle's object


shape.setValues(34,3);

//Display the area of triangle


System.out.println("Area of triangle : " + shape.getArea());
}
}
Output :
Area of rectangle : 390.0
Area of triangle: 51.0
BASIC EXAMPLE FOR INTERFACE1
Instruction to execute Interface program:
1)Create a folder Instruction in myfile.
2)Then save Animal.java,Dog.javaCat.java,Zoo.java in that folder
3)Then compile the program, by entering in Interface folder in Dos
prompt, don’t run the program
4)Atlast,run Zoo.java program

Animal.java:

public interface Animal


{
//Methods without implementation.
String getName();
String makeNoise();
}
Dog.java
public class Dog implements Animal
{
private String name; // To hold name of dog.

//Constructor that accept name as parameter.


public Dog(String name)
{
this.name = name;
}

// method required to implement the animal interface.


public String getName()
{
return name;
}

// method required to implement the animal interface.


public String makeNoise()
{
return "woof! woof!";
}
}
Cat.java
public class Cat implements Animal
{
private String name; // To hold name of cat.

//Constructor that accept name as parameter.


public Cat(String name)
{
this.name = name;
}
// method required to implement the animal interface.
public String getName()
{
return name;
}

// method required to implement the animal interface.


public String makeNoise()
{
return "Meow!";
}
}

Zoo.java:
import java.util.ArrayList;

public class Zoo


{
public static void main(String[] args)
{
// create an ArrayList of animals
ArrayList<Animal> animals = new ArrayList<Animal>();
animals.add(new Dog("Krypto")); // append a Dog object to the list
animals.add(new Cat("Bella")); // append a Cat object to the list
animals.add(new Dog("Rocky")); // append a Dog object to the list
animals.add(new Cat("Molly")); // append a Cat object to the list

// generically process each element in arraylist animals


for (Animal animal: animals)
{
System.out.println(animal.getName()+ " : " + animal.makeNoise());
}
}
}
Output :

Krypto : woof! woof!


Bella : Meow!
Rocky : woof! woof!
Molly : Meow!
EXAMPLE FOR INTERFACE2
2)Create an interface Department containing attributes deptName
and deptHead. It also has abstract methods for printing the
attributes. Create a class hostel containing hostelName,
hostelLocation and numberOfRooms. The class contains method
printing the attributes. Then write Student class extending the
Hostel class and implementing the Department interface. This class
contains attributes studentName, regdNo, electiveSubject and
avgMarks. Write suitable printData method for this class. Also,
implement the abstract methods of the Department interface. Write a
driver class to test the Student class. The program should be menu
driven containing the options:
 Admit new student
 Migrate a student
 Display details of a student
 For the third option, a search is to be made on the basis of the
entered registration number

To create the above interface program follow the instructions as shown below

1)Inside myfile create a folder name interface2

2)Inside interface2 folder,create Department.java interface

3) Inside interface2 folder,create Hostel.java class,Student Master.java

4)In command prompt,inside interface2

compile Department.java
compile Hostel.java,StudentMaster.java

5)Then run Student master.java

public interface Department

public void getDetpName();

public void getDetpHead();

class Hostel

protected String hname,hlocation;

int noofroom;

void getHostelName()

System.out.println("Name Of the Hostel : " + hname);

void getHostelLocation()

System.out.println("Hostel Location : " + hlocation);

void getNoOfRoom()

System.out.println("Total Room : " + noofroom);

import java.util.*;
class Student extends Hostel implements Department

String sname,regno,elesub;

String deptName,deptHead;

int avgMarks;

void getStudentName()

System.out.println("Student : " + sname);

String getStudentRegNo()

return regno;

void getElectiveSubject()

System.out.println("Elective Subject : " + elesub);

void getAvgMarks()

System.out.println("Average Marks : " + avgMarks);

public void getDetpName()

System.out.println("Department Name : " + deptName);

public void getDetpHead()

{
System.out.println("Department Head : " + deptHead);

void addStudent()

Scanner sc=new Scanner(System.in);

System.out.print("Enter Student name : ");

sname=sc.nextLine();

System.out.print("Enter Registration Number : ");

regno=sc.nextLine();

System.out.print("Enter Elective Subject : ");

elesub=sc.nextLine();

System.out.print("Enter Hostel Name : ");

hname=sc.nextLine();

System.out.print("Enter Hostel Location : ");

hlocation=sc.nextLine();

System.out.print("Enter Department Name : ");

deptName=sc.nextLine();

System.out.print("Enter Department Head : ");

deptHead=sc.nextLine();

System.out.print("Enter No of room : ");

noofroom=sc.nextInt();

System.out.print("Enter Avg Marks : ");

avgMarks=sc.nextInt();

void migrate()

Scanner sc=new Scanner(System.in);


System.out.print("Enter new Department Name : ");

deptName=sc.nextLine();

System.out.print("Enter new Department Head : ");

deptHead=sc.nextLine();

void display()

getStudentName();

System.out.println(" Student Registration No is : " + getStudentRegNo());

getElectiveSubject();

getAvgMarks();

getDetpName();

getDetpHead();

import java.util.*;

class StudentMaster

public static void main(String []args)

Scanner sc=new Scanner(System.in);

Student []st=new Student[100];

int sno=0;

String rno;

int ch;

boolean b;
while(true)

System.out.println("\n 1. Admit a student");

System.out.println(" 2. Migrate a student");

System.out.println(" 3. Display");

System.out.println(" 4. Exit");

System.out.println(" 5. Enter Your Choice");

ch=sc.nextInt();

switch(ch)

case 1:

st[sno]=new Student();

st[sno++].addStudent();

break;

case 2:

System.out.println("Enter Registration no : ");

rno=sc.next();

b=false;

for(int i=0;i<sno;i++)

if(st[i].getStudentRegNo().equals(rno))

b=true;

st[0].migrate();

break;

}
if(b==false)

System.out.println("Student Not Found");

break;

case 3:

System.out.println("Enter Registration no : ");

rno=sc.next();

b=false;

for(int i=0;i<sno;i++)

if(st[i].getStudentRegNo().equals(rno))

b=true;

st[0].display();

break;

if(b==false)

System.out.println("Student Not Found");

break;

case 4:

System.exit(0);

default:

System.out.println("--Invalid Entry--");
}

C:\myfile\interface>cd\

C:\>cd myfile

C:\myfile>cd interface2

C:\myfile\interface2>javac Department.java

C:\myfile\interface2>javac Hostel.java

C:\myfile\interface2>javac Student.java

C:\myfile\interface2>javac StudentMaster.java

C:\myfile\interface2>java StudentMaster

1. Admit a student
2. Migrate a student
3. Display
4. Exit
5. Enter Your Choice
1
Enter Student name : ashwini
Enter Registration Number : 444
Enter Elective Subject : graphics
Enter Hostel Name : rose
Enter Hostel Location : chennai
Enter Department Name : mca
Enter Department Head : sundar
Enter No of room : 78
Enter Avg Marks : 90

1. Admit a student
2. Migrate a student
3. Display
4. Exit
5. Enter Your Choice
2
Enter Registration no :
444
Enter new Department Name : bca
Enter new Department Head : vel
1. Admit a student
2. Migrate a student
3. Display
4. Exit
5. Enter Your Choice
3
Enter Registration no :
444
Student : ashwini
Student Registration No is : 444
Elective Subject : graphics
Average Marks : 90
Department Name : bca
Department Head : vel

1. Admit a student
2. Migrate a student
3. Display
4. Exit
5. Enter Your Choice
4

C:\myfile\interface2>

You might also like