Introduction to Computation and Problem Solving

Similar documents
1.00 Lecture 14. Exercise: Plants

CS111: PROGRAMMING LANGUAGE II

Inheritance and Polymorphism

Inheritance and Interfaces

1.00 Lecture 13. Inheritance

CMSC 132: Object-Oriented Programming II. Inheritance

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

Polymorphism and Interfaces. CGS 3416 Spring 2018

Object Oriented Programming. Java-Lecture 11 Polymorphism

First IS-A Relationship: Inheritance

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

Inheritance, Polymorphism, and Interfaces

CS 61B Data Structures and Programming Methodology. July 2, 2008 David Sun

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

Object-Oriented Concepts

OVERRIDING. 7/11/2015 Budditha Hettige 82

Lecture 18 CSE11 Fall 2013 Inheritance

Darrell Bethea June 6, 2011

Chapter 14 Abstract Classes and Interfaces

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

CS111: PROGRAMMING LANGUAGE II

CSC207 Week 3. Larry Zhang

CIS 110: Introduction to computer programming

Polymorphism 2/12/2018. Which statement is correct about overriding private methods in the super class?

Inheritance. OOP: Inheritance 1

Classes and Inheritance Extending Classes, Chapter 5.2

Java Object Oriented Design. CSC207 Fall 2014

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

Inheritance. Unit 8. Summary. 8.1 Inheritance. 8.2 Inheritance: example. Inheritance Overriding of methods and polymorphism The class Object

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Inheritance. Finally, the final keyword. A widely example using inheritance. OOP: Inheritance 1

More Relationships Between Classes

Need to store a list of shapes, each of which could be a circle, rectangle, or triangle

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Inheritance and Interfaces

Topic 7: Inheritance. Reading: JBD Sections CMPS 12A Winter 2009 UCSC

INHERITANCE. Spring 2019

Programming using C# LECTURE 07. Inheritance IS-A and HAS-A Relationships Overloading and Overriding Polymorphism

CMSC 132: Object-Oriented Programming II

Instance Members and Static Members

What is Inheritance?

Java How to Program, 8/e

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance?

Inheritance (Part 5) Odds and ends

Programming II (CS300)

Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal

C09: Interface and Abstract Class and Method

Inheritance and Polymorphism

COE318 Lecture Notes Week 9 (Week of Oct 29, 2012)

CS313D: ADVANCED PROGRAMMING LANGUAGE

Inheritance (Part 2) Notes Chapter 6

BBM 102 Introduction to Programming II Spring Abstract Classes and Interfaces

Inheritance (Outsource: )

Introduction to Computation and Problem Solving

CS 251 Intermediate Programming Inheritance

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

Chapter 10 Classes Continued. Fundamentals of Java

Programming II (CS300)

Lecture 5: Inheritance

CS260 Intro to Java & Android 03.Java Language Basics

8. Polymorphism and Inheritance

CS 11 java track: lecture 3

Java Fundamentals (II)

ASSIGNMENT NO 13. Objectives: To learn and understand concept of Inheritance in Java

COMP 110/L Lecture 19. Kyle Dewey

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

CS-202 Introduction to Object Oriented Programming

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

Informatik II (D-ITET) Tutorial 6

CMSC 132: Object-Oriented Programming II

Person class. A class can be derived from an existing class by using the form

CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

F I N A L E X A M I N A T I O N

Programming in C# Inheritance and Polymorphism

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

CS313D: ADVANCED PROGRAMMING LANGUAGE

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Java and OOP. Part 3 Extending classes. OOP in Java : W. Milner 2005 : Slide 1

ITI Introduction to Computing II

STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

BBM 102 Introduction to Programming II Spring 2017

Inheritance CSC9Y4. Inheritance

Inheritance & Abstract Classes Fall 2018 Margaret Reid-Miller

COE318 Lecture Notes Week 8 (Oct 24, 2011)

Person class. A class can be derived from an existing class by using the form

Practice Questions for Final Exam: Advanced Java Concepts + Additional Questions from Earlier Parts of the Course

Abstract class & Interface

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance

Announcement. Agenda 7/31/2008. Polymorphism, Dynamic Binding and Interface. The class will continue on Tuesday, 12 th August

ITI Introduction to Computing II

Implements vs. Extends When Defining a Class

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor

Lecture 2: Java & Javadoc

Structured Programming

Transcription:

Class 13: Inheritance and Interfaces Introduction to Computation and Problem Solving Prof. Steven R. Lerman and Dr. V. Judson Harward 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 create an instance of it in an application, 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 1

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 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 { }; 4 2

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 (nonabstract) 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 5 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 nonabstract methods, the default will be invoked but may do the wrong thing 6 3

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

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 (or be abstract) You may then invoke methods on this class that rely on the interface. Examples: If your class implements the Comparable interface, you can put objects of your class into arrays and use the Arrays.sort() method You will use interfaces frequently in Swing (GUI) 9 Interface Details Interfaces are like abstract classes but: A subclass can only inherit from only one superclass Multiple interfaces can be implemented in a single class (e.g., Comparable and Cloneable) in your class Instances of interfaces cannot be instantiated Comparable list= new Comparable(); // Error You can declare objects to be of type interface Comparable name; // OK They can be names for objects of a class that implements the interface: Comparable name= new Name(); // 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 10 5

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, SpecGrad classes from Lecture 12 would all need to implement these methods 11 import java.util.*; Interface example 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 12 6

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; } 13 Inheritance- Key Points Inheritance allows a programmer to extend objects that the programmer did not write Access restrictions still hold for the super class If the base class changes private data or members, the subclasses should be unaffected Protected members in superclass allow direct access by subclasses Subclass 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 14 7

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

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. 17 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 18 9

More issues Quadrilateral Rectangle 19 More issues Quadrilateral MoveCorner() Rectangle 20 10

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

Lab Exercise(1) A. Download Electronics.zip : In your web browser go to the Course web site and download the zip file under the heading Lecture13, JavaFiles into a new folder. Unzip Electronics.zip. You should have the following files: Electronic.java CellPhone.java Computer.java Laptop.java 23 Lab Exercise(2) B. Create a new project in Eclipse called Electronics and add all the unzipped files to your 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. 24 12

Class Diagram Computer -cpu : int -memory : int +print() : void Electronic -brand : String -price : double -warranty : int +print() : void +getprice() : double +setprice() : void +getw arranty() : int +setwarranty() : void CellPhone -batterylife : double -webenabled : bool +print() : void Laptop -displaysize : double +print() : void 25 Figure 1 Creating an Array A. In the Electronics project, create a 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: 2500 MHz; Memory: 512 MB; Laptop: Brand: HP N5170; Price: 1500; Warranty: 24 months; CPU speed: 1500 MHz; Memory: 256 MB; Display Size: 15 D. Print out the specifications of all the elements contained in the array. 26 13

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. 27 28 Adding functionality (2) B. Add this functionality to the classes: Note: Electronic class should declare the increaseprice(int percentage) method as abstract. The function must therefore 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'' 14

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 be initialized to 0. 29 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. 30 15