Вы находитесь на странице: 1из 5

CMSC 22: Object-Oriented Programming (Laboratory)

Institute of Computer Science


College of Arts and Sciences, UPLB
1​st​ Semester, SY 2018-19

LAB HANDOUT 07: Types, Casting, and Interfaces


---------------------------------------------------------------------------------------------------------------------------------------------
Objectives:
At the end of the session, the students should be able to:
● Differentiate type and class
● Explain casting
● Create an interface
● Create a class that implements an interface; including multiple interfaces
● Explain the effects of interfaces
---------------------------------------------------------------------------------------------------------------------------------------------
Java Interface
An interface is one way to ensure that a class can perform certain methods. It is a list of return type and method
signatures which are to be given a method body by classes implementing the interface.

​ nterface​ Expandable{
public i // use keyword interface instead of class
int EXPANSION_COST = 300; // public final static attribute
boolean expand(); // public abstract method/s
}

​ nterface​ Rectangular{
public i
int getArea();
int getPerimeter();
}

In declaring an interface, the keyword ​interface​ is used.

Interfaces cannot be instantiated, they can only be implemented. All the methods in an interface are abstract methods
(i.e., we leave the implementation of the methods in the interface to the implementing classes), so there is no need to
state it. Interfaces can only contain final and static attributes, or simply constants, that can be accessed by the
implementing classes.
Question: What is the access modifier of all the abstract methods in an interface?

Implementing Interfaces
When implementing an interface, we use the keyword ​implements ​followed by the interface name. Once a class
implements an interface, it must provide an implementation to ​all​ the method signatures found in the interface.

public class VirtualCity ​implements Expandable​{


public boolean expand() {
// implementation body
}
}

A class can implement ​multiple ​interfaces. In doing so, the implementing class must define all the method signatures
found in all the interfaces that it is implementing.

public class VirtualCity ​implements Expandable, Rectangular​{


public boolean expand(){/*implementation*/}
public int getArea(){/*implementation*/}
public int getPerimeter(){/*implementation*/}
}
Sample Problem Domain

A city has its name and population. Population grows by adding creatures, only one at a time, in the city.

A virtual city is a city that should be rectangular in shape and should be expandable. It has a name, length, width,
population count, and money. Initially, the virtual city has a total amount of 500 and its length and width are 3 and 2
respectively. Each creature occupies one (1) square unit of a virtual city. Number of creatures may be added to the
city provided that its area is still enough to accommodate more creatures. A creature adds 60 to the total money of the
virtual city.

A rectangular city should be able to compute for its area and its perimeter. An expandable city can expand. Cost of
expansion amounts to 300. This will add 1 unit each for the length and width.

Information about a city and a virtual city can be known by anyone.

City.java
package city;

public class City {


String name;
int population;

public City(String name){


this.name = name;
}

public void addCreature(){


this.population++;
}

public String getName(){


return this.name;
}
}
 
Rectangular.java
package city;

public interface Rectangular {


int getArea();
int getPerimeter();
}

Expandable.java
package city;

public interface Expandable {


int EXPANSION_COST = 300;
boolean expand();
}
VirtualCity.java
package city;

public class VirtualCity extends City implements Rectangular, Expandable {


private int length;
private int width;
private int money;

public static final boolean SUCCESSFUL = true;


public static final int INITIAL_LENGTH = 3;
public static final int INITIAL_WIDTH = 2;
public static final int INITIAL_MONEY = 500;

public VirtualCity(String name){


super(name);
this.length = VirtualCity.INITIAL_LENGTH;
this.width = VirtualCity.INITIAL_WIDTH;
this.money = VirtualCity.INITIAL_MONEY;
}

public void addCreature(){


if(this.getArea()>=(this.population+1)){
super.addCreature();
this.money += 60;
System.out.println("Successfully added a creature");
}else System.out.println("Not enough area to add creatures.");
}

public int getArea(){


return this.length * this.width;
}

public int getPerimeter(){


return (2*this.length) + (2 * this.width);
}

public boolean expand(){


if(this.money >= Expandable.EXPANSION_COST){
this.length++;
this.width++;
this.money -= Expandable.EXPANSION_COST;
return VirtualCity.SUCCESSFUL;
}
return !VirtualCity.SUCCESSFUL;
}

public int getLength(){


return this.length;
}

public int getWidth(){


return this.width;
}

 
Effects of Interface
Implementing multiple interfaces can give the illusion that a class is able to employ multiple inheritance. It gives such
an illusion because in terms of typing, instances of the implementing class can be casted to the types of all the
interfaces it implements. Just like in inheritance where instances of the subclass can be casted to the type of the
superclass. However, nothing is really inherited by the implementing class from the interface; the interface merely
imposes to the implementing class what behaviors or methods it should support.

public class VirtualCity ​extends City implements Rectangular, Expandable​ { … }

A VirtualCity is a City, Rectangular, Expandable.

Class vis-a-vis Type


The ​type of the object determines what operations it can perform; on the other hand, the ​class of the object
determines the implementation of its methods.

<Type>​ <instanceName> = new ​<Class>​();

Example:
public class VirtualCity ​extends City implements Rectangular, Expandable​ { … }

Types of VirtualCity instances can be a ​VirtualCity, City​,​ Rectangular​ or ​Expandable​.

Casting
Casting can be performed in order to limit the valid operations an object can perform to operations warranted by the
type it is casted to. Java supports widening conversions; that is, instances of a subclass can be casted to the type of
the superclass. Narrowing conversions are possible if and only if the object came from a preceding widening
conversion. In the case of interfaces, the instances of the implementing class can be casted to the type of its
interfaces. See the following example:

Instantiation

VirtualCity city = new VirtualCity(“Los Banos”); Type is same as class.

City city = new VirtualCity(“Los Banos”); Type is the superclass of VirtualCity (casting)

Rectangular city = new VirtualCity(“Los Banos”); Type is an interface implemented by VirtualCity


(casting)

Expandable city = new VirtualCity(“Los Banos”); Type is an interface implemented by VirtualCity


(casting)

Main.java
import city.City;
import city.Rectangular;
import city.Expandable;
import city.VirtualCity;

public class Main {


public static void main(String[] args){
VirtualCity a = new VirtualCity("Calamba");
City b = new VirtualCity("Calamba");
Rectangular c = new VirtualCity("Calamba");
Expandable d = new VirtualCity("Calamba");

System.out.println(a.getName());
System.out.println(b.getName());
System.out.println(c.getArea());
System.out.println(d.expand());

a.addCreature();

//What implementation of addCreature was executed? (City's or VirtualCity's?)


b.addCreature();

//These will produce errors due to their types.


//System.out.println(c.getName());
//System.out.println(d.getWidth());

}
}

Since c is of type ​Rectangular​, the operations it can invoke are only ​getArea() and ​getPerimeter()​. The method
expand()​ cannot be invoked by c because the operations allowed are limited by its type.

Вам также может понравиться