Presentation is loading. Please wait.

Presentation is loading. Please wait.

Inheritance, Interfaces

Similar presentations


Presentation on theme: "Inheritance, Interfaces"— Presentation transcript:

1 Inheritance, Interfaces
1.00 Lecture 13 Inheritance, Interfaces

2 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

3 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

4 Shape class abstract 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 {…};

5 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

6 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

7 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!

8 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( )

9 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)

10 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

11 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

12 Interface example import 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

13 Interface example, p.2 class 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; }

14 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

15 Fun with animals class Bird { public void fly(); // Birds can fly … };

16 Fun with animals class Bird { public void fly( ); // Birds can fly
… }; class Penguin extends Bird { // Penguins are birds

17 Fun with animals class 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.

18 Possible solutions Decision depends on use of system:
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

19 More issues Quadrilateral Rectangle

20 More issues Quadrilateral MoveCorner() Rectangle

21 More issues Quadrilateral MoveCorner() Rectangle MoveCorner()

22 More issues Quadrilateral MoveCorner() Rectangle MoveCorner()
Must override the MoveCorner() method in subclasses to move multiple corners to preserve the correct shape

23 Exercise 1 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 one) – 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.

24 Hands On Create a project called Vehicle and add the Vehicle.java file
and the VehicleTest.java to your project (to add a file to your project, 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.

25 Create a Car class Vehicle
• 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 Parent class "is-a" Car Child class

26 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

27 Create a Car class (3) Print the car information after the bike information. 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 in it: Member brand Inherited from Vehicle model Inherited from Vehicle type Inherited from Vehicle cylinders Defined in Car seats Defined in Car print( ) Inherited from Vehicle

28 Overriding Print() We need a new print() method for the Car class that prints all its data members including cylinders and seats. 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. 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;

29 Exercise 2 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.

30 Exercise 2 B. 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.

31 Class Diagram Electronic -brand : String -price : double
-warranty : int +print() : void +getPrice() : double +setPrice() : void +getW arranty() : int +setW arranty() : void CellPhone Computer -batteryLife : double -webEnabled : bool -cpu : int -memory : int +print() : void +print() : void Laptop -displaySize : double +print() : void Figure 1

32 Creating an Array A. 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.

33 Adding Functionality 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.

34 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''

35 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.

36 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.


Download ppt "Inheritance, Interfaces"

Similar presentations


Ads by Google