1.00 lecture 13 inheritance, interfaces. more on abstract classes classes can be very general at the...

36
1.00 Lecture 13 Inheritance, Interfaces

Upload: amelia-taylor

Post on 27-Mar-2015

225 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

1.00 Lecture 13

Inheritance, Interfaces

Page 2: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

More on Abstract Classes

• Classes can be very general at the top of a class hierarchy. – For example, MIT could have a class Person, from which Employees, Students, Visitors, etc. inherit – Person is too abstract a class for MIT to ever use in a computer system but it can hold name, address, status, etc. that is in common to all the subclasses – We can make Person an abstract class: Person objects cannot be created, but subclass objects, such as Student, can be

• Classes can be concrete or abstract

Page 3: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

Abstract Classes, p.2• Another example (leading to graphics in the next lectures) – Shape class in a graphics system – Shapes are too general to draw; we only know how to draw specific shapes like circles or rectangles – Shape abstract class can define a common set of methods that all shapes must implement, so the graphics system can count on certain things being available in every concrete class – Shape abstract class can implement some methods that every subclass must use, for consistency: e.g., object ID, object type

Page 4: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

Shape classabstract class Shape { public abstract void draw(); // Drawing function must be implemented in each // derived class but no default is possible: abstract

public void error(String message); // Error function must be implemented in each derived // class and a default is available: non-abstract method

public final int objectID(); // Object ID function: each derived class must have one // and must use this implementation: final method

…};

class Square extends Shape {…};class Circle extends Shape {…};

Page 5: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

Abstract method

• Shape is an abstract class (keyword)

• Shape has an abstract method draw() • No objects of type Shape can be created

• draw( ) must be redeclared by any concrete (non-

abstract) class that inherits it

• There is no definition of draw( ) in Shape – This says that all Shapes must be drawable, but the Shape class has no idea of how to draw specific shapes

Page 6: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

Non-abstract method

• Shape has a non-abstract method error( ) – Every derived class must have an error method

– Each derived class may handle errors as it

wishes: • It may define its own error function using this interface

(method arguments/return value)

• It may use the super class implementation as a default

– This can be dangerous: if new derived classes are

added and programmers fail to redefine non-

abstract methods, the default will be invoked but

may do the wrong thing

Page 7: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

Final method

• Shape has a final method objectID – Final method is invariant across derived classes – Behavior is not supposed to change, no matter how specialized the derived class becomes

• Super classes should have a mix of methods – Don’t make all abstract super class methods abstract. Take a stand!

Page 8: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

Preventing Inheritance

• To prevent someone from inheriting from your class, declare it final: final class Grad extends Student { … • This would not allow SpecGrad to be built • (Class can have abstract, final or no keyword)

– You can also prevent individual methods from being overridden (redefined) in subclasses by declaring them final final void getData( ) { …

• This would not allow a subclass to redefine getData( )

Page 9: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

Interface Definition

• Interface is a specification for a set of methods a class must implement – Interfaces specify but do not implement methods – A class that implements the interface must implement all its methods – You may then invoke methods on this class that rely on the interface. Examples: • If your class implements the Comparable or Comparator interface, you can put objects of your class into Arrays and use the Arrays.sort() method • You will use interfaces frequently in Swing (GUI)

Page 10: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

Interface Details• Interfaces are like an abstract class but: – If they were implemented as an abstract class, a subclass could only inherit from one superclass – Multiple interfaces can be inherited (e.g., Comparable and Cloneable) in your class – Interfaces cannot be instantiated Comparable list= new Comparable( ); // Error

– You can declare objects to be of type interface Comparable list; // OK

– They can be names for objects of a class that implements the interface: Comparable list= new MySortClass( ); // OK

– Interfaces may contain methods and constants public interface Rotatable { void rotate(double theta); // List reqd methods double MAX_ROTATE= 360; } // Implicitly final // Methods and fields default to be public

Page 11: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

Interfaces and inheritance

• Interfaces can be inherited – Scholarship program eligibility public interface Eligible { boolean IsEligible(double age, double income); } – Scholarship program actual selection public interface Selected extends Eligible { boolean IsSelected(double gpa, double terms); } – Our student program could have a scholarship selection class that operates on objects of Student classes that implement one or both of these interfaces • Undergrad, grad, special grad classes would all need to implement these methods

Page 12: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

Interface exampleimport java.util.*;

public class Interface1 { public static void main(String[] args) { Student[ ] list= new Student[4]; list[0]= new Student("Mary", 6); list[1]= new Student("Joan", 4); list[2]= new Student("Anna", 8); list[3]= new Student("John", 2); Arrays.sort(list); for (int i= 0; i < list.length; i++) { Student s= list[i]; System.out.println(s.getName() + " " + s.getTerms()); } }} // Look up Comparable interface in Javadoc

Page 13: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

Interface example, p.2class Student implements Comparable { // Reqd by Arrays.sort public Student(String n, int t) { name= n; terms= t; } public String getName() { return name; } public int getTerms() { return terms; } public int compareTo(Object b) { // Reqd by Comparable Student two= (Student) b; if (terms < two.terms) return -1; else if (terms > two.terms) return 1; else return 0; } private String name; private int terms;}

Page 14: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

Inheritance- Key Points• Inheritance allows a programmer to extend objects that she did not write – Access restrictions still hold for the super class • If the base class changes private data or members, the sub classes should be unaffected

– Protected members in super class allow direct access by sub classes • Must not change in super class; must be designed with intent to allow use by sub classes

– Sub class has all data (private, protected and public) of the super class. Each object has all this data. • Sub class can use only public and protected methods and data of the super class, not private methods or data

– All Java® objects inherit implicitly from class Object • Java® libraries, Java® documentation use Object frequently

Page 15: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

Fun with animals

class Bird { public void fly(); // Birds can fly … };

Page 16: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

Fun with animals

class Bird { public void fly( ); // Birds can fly … };

class Penguin extends Bird { // Penguins are birds… };

Page 17: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

Fun with animalsclass Bird { public void fly( ); // Birds can fly … };class Penguin extends Bird { // Penguins are birds… };// Problems:// If super class fly( ) is final, Penguins must fly

// If super class fly( ) is abstract or non-abstract,// Penguin’s fly( ) can print an error, etc. It’s clumsy

// With inheritance, every subclass has every method and// data field in the superclass. You can never drop// anything. This is a design challenge in real system.

Page 18: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

Possible solutions

Bird Bird

Penguin Crow FlyingBird NonFlyingBird

Crow Penguin

Decision depends on use of system: If you’re studying beaks, difference between flying and not flying may not matter

Page 19: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

More issues

Quadrilateral

Rectangle

Page 20: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

More issues

Quadrilateral

Rectangle

MoveCorner()

Page 21: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

More issues

Quadrilateral

Rectangle

MoveCorner()

MoveCorner()

Page 22: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

More issues

Quadrilateral

Rectangle

MoveCorner()

MoveCorner()

Must override the MoveCorner() method in subclasses to move

multiple corners to preserve the correct shape

Page 23: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

Exercise 1A. Download Vehicle.java and VehicleTest.java :

– You need to get the path of your mounted directory: In the Explorer view, Click on the FileSystems tab. The path of your mounted directory is displayed as a link in your Filesystems tree (if you have several mounted directories, pick the top on

e)

– In your web browser go to: Vehicle.java

Save the downloaded file in your mounted directory. (Right click, ‘Save Link As’)

– Do the same with: VehicleTest.java

– Return to the Explorer view to FileSystems. Right-click on the mounted directory and choose refresh. The newly saved file should appear.

Page 24: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

Hands OnA. Create a project called Vehicle and add the Vehicle.java file and the VehicleTest.java to your project (to add a file to your proje

ct, right-click on the file and choose Tools->Add To Project).

B. The following is a summary of the Vehicle class that you have downloaded:

– String brand: Brand of the vehicle (e.g. Honda) – String model: Model of the vehicle (e.g. Accord) – String type: Type of the vehicle (e.g. Sedan) – print(): Prints the vehicle properties.

• The main( ) in VehicleTest.java creates a bike (which is a vehicle object) and prints its properties. Compile and run your program to test your vehicle class.

Page 25: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

Create a Car class

• The Vehicle class has basic information in it, and would be OK for bikes. But a car, which is a vehicle, needs more information. We want make a class called Car, which in addition to the basic properties that are contained in the Vehicle class, has two additional fields: the number of cylinders and number of seats. The relationship between Vehicle and Car is shown below:

Vehicle

Car

"is-a"

Parent class

Child class

Page 26: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

Create a Car class (2)A. Create the class Car that extends Vehicle. The Car class should have the following members: – int cylinders: number of cylinders in the engine – int seats: number of seats. – A constructor that initializes the brand, model, type, cylinders and seats data members of a car object.

Don’t add a print() method to the Car class yet.

• In the VehicleTest class, instantiate a car object with the following properties: – Brand: BMW – Model: 330i – Type: Sports Car – Cylinders: 6 – Seats: 5

Page 27: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

Create a Car class (3)

C. Print the car information after the bike information.

D. Compile and run. You should have the following output:

Brand: GT; Model:01-IDrive 2.0; Type: Moutain Bike;

Brand: BMW; Model: 330i; Type: Sports Car:

So far, an object of type Car has the following members init:

Member

brand

model

type

cylinders

seats

print( )

Inherited from Vehicle

Inherited from Vehicle

Inherited from Vehicle

Defined in Car

Defined in Car

Inherited from Vehicle

Page 28: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

Overriding Print()A. We need a new print() method for the Car class that prints all its data members including cylinders and seats.

B. In the Car class, override the print() method of the parent class. A child overrides a method from its parent by defining a replacement method with the same signature.

C. Compile and run your program. You should have the following output:

Brand: GT; Model: 01-IDrive 2.0; Type: Moutain Bike;

Brand: BMW; Model: 330i; Type: Sports Car; Cylinders: 6; Seats: 5;

Page 29: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

Exercise 2A. Download Electronics.zip :

– In your web browser go to: Electronics.zip Save the downloaded file in your mounted directory. (Right click, ‘Save Link As’)

– Unzip Electronics.zip and move all the unzipped files to your mounted directory. You should have the following files: • Electronic.java • CellPhone.java • Computer.java • Laptop.java

– Return to the Explorer view to FileSystems. Right-click on the mounted directory and choose refresh. The newly saved file should appear.

Page 30: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

Exercise 2B. Create a project called Electronics and add all the unzipped files to your project (to add a file to your project, right-click on the file and choose Tools->Add To Project).

C. Figure 1 is the class diagram of the Electronics project. It shows the relationship between the classes, and it shows all their data fields. • Electronic, the parent class of Computer and Cellphone, is an abstract class. • Computer is the parent class of Laptop, but is not abstract. This means that you can instantiate an object of type Computer (which will represent in our case a desktop computer).

Take a look at the class diagram and make sure it is consistent with the java® classes you have downloaded.

Page 31: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

Class Diagram

+print() : void+getPrice() : double+setPrice() : void+getW arranty() : int+setW arranty() : void

Electronic

-brand : String -price : double -warranty : int

-cpu : int-memory : int

Computer

+print() : void

-displaySize : double

+print() : void

Laptop

+print() : void

CellPhone-batteryLife : double-webEnabled : bool

Figure 1

Page 32: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

Creating an ArrayA. In the Electronics project, create a Main class called ElectronicMain with an empty main() method.

B. In the main() method, create an array that can hold three objects of type Electronic.

C. Add to this array three objects with the following specifications: • Cell phone: Brand: Nokia TS200; Price: $300; Warranty: 18 months; Battery Life: 3.5Hr; Web Enabled: true; • Desktop (Computer): Brand: Dell D2100; Price: 1000; Warranty: 24 months; CPU speed: 1500 MHz; Memory: 512 MB; • Laptop: Brand: HP N5170; Price: 1500; Warranty: 24 months; CPU speed: 900 MHz; Memory: 256 MB; Display Size: 15’’

D. Print out the specifications of all the elements contained in the array.

Page 33: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

Adding Functionality

A. We need a method to increase the price of an electronic device by a given percentage. The method should have the following signature:

public void increasePrice(int percentage)

• This method doesn’t behave the same for all electronic devices: • When a computer’s price is increased by any percentage, its warranty is increased by 12 months. • When a cell phone’s price is increased by any percentage, its warranty is increased by 6 months.

Page 34: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

Adding functionality (2)B. Add this functionality to the classes: • Note: Electronic class should declare the increasePrice(int percentage) method as abstract, and therefore, the function must be implemented in each of the derived classes.

C. In the main() method, increase the price of all the elements in the array by 5%. Print the all the elements again. The output should be the following: - Brand: Nokia TS200; Price: $315.0; Warranty: 24 months Battery Life: 3.5Hr; Web Enabled: true - Brand: Dell D2100; Price: $1050.0; Warranty: 36 months CPU Speed: 1500MHz; Memory Size: 512MB - Brand: HP N5170; Price: $1575.0; Warranty: 36 months CPU Speed: 900MHz; Memory Size: 256MB Display Size: 15.0''

Page 35: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

Counting Electronic devices(Optional)

A. We need to keep track of the number of electronic devices we have created. You should add the following data fields in the appropriate classes: • numberElectronics • numberCellPhones • numberComputers • numberLaptops

These data fields should originally be initialized to 0.

Page 36: 1.00 Lecture 13 Inheritance, Interfaces. More on Abstract Classes Classes can be very general at the top of a class hierarchy. – For example, MIT could

Counting Electronic devices(Optional)

B. Every time a new object is created, the appropriate counters should be incremented by 1. Taking our array example you should have: • numberElectronics = 3 • numberCellPhones = 1 • numberComputers = 2 (Remember that a Laptop is a Computer) • numberLaptops = 1

C. In each of the classes, create a method getCount() that returns the class counter. You should be able to call getCount() without instantiating any object.

D. In the main() method, call the getCount() function of all the classes (Electronic, CellPhone, Computer and Laptop). Compile and run.