Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Lab-2 - Interfaces

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

PCO692C EES, University Polytechnic, AMU

PCO692C, Object Oriented Programming Lab-II


Experiment No. 2

Objective:
Develop the Java programs to demonstrate the use of interfaces.

Theory:

Interfaces in Java
An Interface in Java programming language is defined as an abstract type used to specify the
behavior of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains
static constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in
the Java interface, not the method body. It is used to achieve abstraction and multiple inheritance
in Java. In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body. Java Interface also represents the IS-A relationship. When we decide a
type of entity by its behaviour and not via attribute we should define it as an interface.

Like a class, an interface can have methods and variables, but the methods declared in an interface
are by default abstract (only method signature, no body).

• Interfaces specify what a class must do and not how. It is the blueprint of the behaviour.
• Interface do not have constructor.
• Represent behaviour as interface unless every sub-type of the class is guaranteed to have
that behaviour.
• An Interface is about capabilities like a Player may be an interface and any class
implementing Player must be able to (or must implement) move(). So it specifies a set of
methods that the class has to implement.
• If a class implements an interface and does not provide method bodies for all functions
specified in the interface, then the class must be declared abstract.
• A Java library example is Comparator Interface. If a class implements this interface, then it
can be used to sort a collection.
Syntax:

Interface name {
// declare constant fields
// declare methods that abstract
// by default.
}

29
PCO692C EES, University Polytechnic, AMU

To declare an interface, use the interface keyword. It is used to provide total abstraction. That
means all the methods in an interface are declared with an empty body and are public and all fields
are public, static, and final by default. A class that implements an interface must implement all the
methods declared in the interface. To implement interface use implements keyword.

Why do we use an Interface?


• It is used to achieve total abstraction.
• Since java does not support multiple inheritances in the case of class, by using an interface
it can achieve multiple inheritances.
• Any class can extend only 1 class but can any class implement infinite number of interface.
• It is also used to achieve loose coupling.
• Interfaces are used to implement abstraction. So the question arises why use interfaces
when we have abstract classes?
• The reason is, abstract classes may contain non-final variables, whereas variables in the
interface are final, public and static.

// A simple interface
interface Player {
final int id = 10;
int move();
}

Difference Between Class and Interface


The major differences between a class and an interface are:

1. In class, you can instantiate variables and create an object. In an interface, you can’t
instantiate variables and create an object.
2. Class can contain concrete(with implementation) methods. The interface cannot contain
concrete(with implementation) methods
3. The access specifiers used with classes are private, protected, and public. In Interface only
one specifier is used- Public.

Implementation: To implement an interface we use the keyword implements

// Java program to demonstrate working of interface


import java.io.*;

// A simple interface
interface In1 {

// public, static and final


final int a = 10;

// public and abstract


void display();
}

30
PCO692C EES, University Polytechnic, AMU

// A class that implements the interface.


class TestClass implements In1 {

// Implementing the capabilities of interface.


public void display(){
System.out.println("Hello");
}

// Driver Code
public static void main(String[] args) {
TestClass t = new TestClass();
t.display();
System.out.println(a);
}
}
Output
Hello
10

Real-World Example: Let’s consider the example of vehicles like bicycle, car, bike etc., they
have common functionalities. So we make an interface and put all these common functionalities.
And let Bicycle, Bike, Car etc. implement all these functionalities in their own class in their own
way.

// Java program to demonstrate the real-world example of Interfaces


import java.io.*;

interface Vehicle {
// all are the abstract methods.
void changeGear(int a);
void speedUp(int a);
void applyBrakes(int a);
}

class Bicycle implements Vehicle {


int speed;
int gear;

// to change gear
@Override
public void changeGear(int newGear) {
gear = newGear;
}

// to increase speed
@Override
public void speedUp(int increment){
speed = speed + increment;
}

31
PCO692C EES, University Polytechnic, AMU

// to decrease speed
@Override
public void applyBrakes(int decrement){
speed = speed - decrement;
}

public void printStates() {


System.out.println("speed: " + speed + " gear: " + gear);
}
}

class Bike implements Vehicle {

int speed;
int gear;

// to change gear
@Override
public void changeGear(int newGear){
gear = newGear;
}

// to increase speed
@Override
public void speedUp(int increment){
speed = speed + increment;
}

// to decrease speed
@Override
public void applyBrakes(int decrement){
speed = speed - decrement;
}

public void printStates() {


System.out.println("speed: " + speed+ " gear: " + gear);
}

}
class VehicleDemo {
public static void main (String[] args) {

// creating an inatance of Bicycle


// doing some operations
Bicycle bicycle = new Bicycle();
bicycle.changeGear(2);
bicycle.speedUp(3);
bicycle.applyBrakes(1);

System.out.println("Bicycle present state :");


bicycle.printStates();

32
PCO692C EES, University Polytechnic, AMU

// creating instance of the bike.


Bike bike = new Bike();
bike.changeGear(1);
bike.speedUp(4);
bike.applyBrakes(3);

System.out.println("Bike present state :");


bike.printStates();
}
}
Output
Bicycle present state :
speed: 2 gear: 2
Bike present state :
speed: 1 gear: 1

Advantages of Interfaces in Java

• Without bothering about the implementation part, we can achieve the security of the
implementation.
• In Java, multiple inheritances is not allowed, however, you can use an interface to make use
of it as you can implement more than one interface.

33
PCO692C EES, University Polytechnic, AMU

Exercise 1:

1. Write PersonInterface.java as shown below. PersonInterface is a Java interface.


package ENo_PersonInterfacePkg;

public interface PersonInterface {


// Compute person's total wealth
int computeTotalWealth();

// Get person's name


String getName();
}

2. Write Person.java . The Person class implements the PersonInterface interface.


package ENo_PersonInterface;
public class Person implements PersonInterface {

int cashSaving;
int retirementFund;
String firstName;
String lastName;

// Constructor with arguments


Person(int cashSaving,
int retirementFund,
String firstName,
String lastName){
this.cashSaving = cashSaving;
this.retirementFund = retirementFund;
this.firstName = firstName;
this.lastName = lastName;
}

// Compute person's total wealth


public int computeTotalWealth(){
System.out.println((cashSaving + retirementFund));
return (cashSaving + retirementFund);
}

// Get person's name


public String getName(){
return firstName + " " + lastName;
}
}

3. Create Main.java as shown below.


package ENo_PersonInterfacePkg;
public class Main {
public static void main(String[] args) {
// Create an object instance of Person class.
Person person1 = new Person(10000, 20000, "Arif", "Khan");

// You can assign the object instance to PersonInterface type.


PersonInterface personinterface1 = person1;

34
PCO692C EES, University Polytechnic, AMU

// Display data from person1 and personinterface1.


// Observe that they refer to the same object instance.
System.out.println("person1.getName() = " + person1.getName() + "," +
" person1.computeTotalWealth() = " + person1.computeTotalWealth());

System.out.println("personinterface1.getName() = " +
personinterface1.getName() + "," +
" personinterface1.computeTotalWealth() = " +
personinterface1.computeTotalWealth());

// Check of object instance that is referred by person1 and


// personinterface1 is the same object instance.
boolean b1 = (person1 == personinterface1);
System.out.println("Do person1 and personinterface1 point to the same
object instance? " + b1);

// Create an object instance of Person class


// and assign it to the interface type directly.
PersonInterface personinterface2 = new Person(3000, 4000, "Dadu",
"Daniel");

System.out.println("personinterface2.getName() = " +
personinterface2.getName() + "," +
" personinterface2.computeTotalWealth() = " +
personinterface2.computeTotalWealth());
boolean b2 = (person1 == personinterface2);
System.out.println("Do person1 and personinterface2 point to the same
object instance? " + b2);
}
}

4. Compile and run the program.


3000
person1.getName() = Arif Khan, person1.computeTotalWealth() = 30000
30000
personinterface1.getName() = Arif Khan, personinterface1.computeTotalWealth() =
30000
Do person1 and personinterface1 point to the same object instance? true
7000
personinterface2.getName() = Dadu Daniel, personinterface2.computeTotalWealth()
= 7000
Do person1 and personinterface2 point to the same object instance? false

35
PCO692C EES, University Polytechnic, AMU

Exercise 2:

Develop a Java program that uses the Relation interface.

1. Create RelationInterface Java interface in the file RelationInterface.java as shown


below.
package ENo_RelationInterfacePkg;

// Define an interface with three abstract methods.


// Any class that implements this interface has to
// implement all three methods.
public interface RelationInterface {
public boolean isGreater( Object a, Object b);
public boolean isLess( Object a, Object b);
public boolean isEqual( Object a, Object b);
}

2. Write Line.java . The class implements the Line RelationInterface interface


package ENo_RelationInterfacePkg;

public class Line implements RelationInterface{

private double x1;


private double x2;
private double y1;
private double y2;

// Constructor methoe of the Line class.


public Line(double x1,double x2,double y1,double y2){
this.x1 = x1;
this.x2 = x2;
this.y1 = y1;
this.y2 = y2;
}

// A new method definition of the Line class


public double getLength(){
double length = Math.sqrt( (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));
return length;
}

// Implement isGreater(..) method defined in the Relation interface


public boolean isGreater( Object a, Object b){
double aLen = ((Line)a).getLength();
double bLen = ((Line)b).getLength();
return (aLen > bLen);
}

// Implement isLess(..) method defined in the Relation interface


public boolean isLess( Object a, Object b){
double aLen = ((Line)a).getLength();
double bLen = ((Line)b).getLength();
return (aLen < bLen);
}

36
PCO692C EES, University Polytechnic, AMU

// Implement isEqual(..) method defined in the Relation interface


public boolean isEqual( Object a, Object b){
double aLen = ((Line)a).getLength();
double bLen = ((Line)b).getLength();
return (aLen == bLen);
}
}

3. Create Main.java as shown below.


package ENo_RelationInterfacePkg;
public class Main {
public static void main(String[] args) {
// Create two Line object instances.
Line line1 = new Line(1.0, 2.0, 1.0, 2.0);
Line line2 = new Line(2.0, 3.0, 2.0, 3.0);

boolean b1 = line1.isGreater(line1, line2);


System.out.println("line1 is greater than line2: " + b1);
boolean b2 = line1.isEqual(line1, line2);
System.out.println("line1 is equal with line2: " + b2);

// Note that the line3 is object instance of Line type.


// Because the Line type is also a type of RelationInterface,
// the line3 variable can be declared as RelationInterface type.
// This is a very very important concept you need to understand.
RelationInterface line3 = new Line(1.0, 5.0, 1.0, 5.0);
boolean b3 = line3.isEqual(line1, line3);
System.out.println("line1 is equal with line3: " + b3);

System.out.println("Length of line1 is " + line1.getLength());


System.out.println("Length of line2 is " + line2.getLength());

// The following line of code will generate a compile error since line3
// is declared as RelationInterface interface type not Line type
// and the getLength() method is not one of the methods defined
// in the RelationInterface interface. It is commented out for now.
// System.out.println("Length of line3 is " + line3.getLength());
}
}
4. Compile and run the program
line1 is greater than line2: false
line1 is equal with line2: true
line1 is equal with line3: false
Length of line1 is 1.4142135623730951
Length of line2 is 1.4142135623730951

5. Uncomment the last commented line of Main.java containing line3.getLength() and note
the compiler error. Understand why the compiler error occurs.

37
PCO692C EES, University Polytechnic, AMU

Exercise 3: Implementing various Interfaces.

1. Write AnotherInterfaceExample.java. The AnotherInterfaceExample interface is the


second Java interface that need to be added to your program.
package ENo_PersonInterfacePkg;

public interface AnotherInterfaceExample {


// Measure person's intelligence
int measureIntelligence(String name);
}

2. Modify Person.java as shown below. The change is that the Person class implements the
AnotherInterfaceExample interface in addition to the PersonInterface interface. The code
snippet that is required to be added is shown in blue.
package ENo_PersonInterfacePkg;

public class Person implements PersonInterface, AnotherInterfaceExample{


int cashSaving;
int retirementFund;
String firstName;
String lastName;

// Constructor with arguments


Person(int cashSaving,
int retirementFund,
String firstName,
String lastName){
this.cashSaving = cashSaving;
this.retirementFund = retirementFund;
this.firstName = firstName;
this.lastName = lastName;
}

// Compute person's total wealth


public int computeTotalWealth(){
System.out.println((cashSaving + retirementFund));;
return (cashSaving + retirementFund);
}
// Get person's name
public String getName(){
return firstName + " " + lastName;
}

// Implement method of AnotherInterfaceExample


public int measureIntelligence(String name){
if (name.startsWith("smart")){
return 100;
}
else{
return 50;
}
}
}

38
PCO692C EES, University Polytechnic, AMU

3. Modify Main.java as shown below. The change is so that the instance of the object of class
Person calls the method defined in the new interface. The code snippet that needs to be changed is
shown in blue.
package ENo_PersonInterfacePkg;

public class Main {

public static void main(String[] args) {


// Create an object instance of Person class.
Person person1 = new Person(10000, 20000, "Sang", "Shin");

// You can assign the object instance to


// PersonInterface type.
PersonInterface personinterface1 = person1;

// Display data from person1 and personinterface1.


// Observe that they refer to the same object instance.
System.out.println("person1.getName() = " + person1.getName() + "," +
" person1.computeTotalWealth() = " + person1.computeTotalWealth() +
"," +
" person1.measureIntelligence() = " +
person1.measureIntelligence(person1.getName()));

System.out.println("personinterface1.getName() = " +
personinterface1.getName() + "," +
" personinterface1.computeTotalWealth() = " +
personinterface1.computeTotalWealth());

// Compile error is expected on the following line of code.


// personinterface1.measureIntelligence(personinterface1.getName());

// You can assign the object instance to


// AnotherInterfaceExample type.
AnotherInterfaceExample anotherinterfaceexample1 = person1;

// Check of object instance that is referred by personinterface1 and


// anotherinterfaceexample1 is the same object instance.
boolean b1 = (personinterface1 == anotherinterfaceexample1);
System.out.println("Do personinterface1 and anotherinterfaceexample1
point to the same object instance? " + b1);

}
}

4. Compile and run the program.


30000
person1.getName() = Sang Shin, person1.computeTotalWealth() = 30000,
person1.measureIntelligence() = 50
30000
personinterface1.getName() = Sang Shin, personinterface1.computeTotalWealth() =
30000
Do personinterface1 and anotherinterfaceexample1 point to the same object
instance? true

39
PCO692C EES, University Polytechnic, AMU

5. Add a third interface with the following method


int computeFirstNameLength(String name);

6. Make the Person class implement the interface

The implementation of computeFirstNameLength(String name) returns the length of the first


name

7. Modify Main.java to display the information properly

40

You might also like