chapter 3 inheritance and polymorphism goals: 1.superclasses and subclasses 2.inheritance hierarchy...

28
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes 6.Interfaces 7.The Comparable Interface

Upload: alaina-franklin

Post on 04-Jan-2016

226 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes

Chapter 3

Inheritance and PolymorphismGoals:1. Superclasses and subclasses2. Inheritance Hierarchy3. Polymorphism4. Type Compatibility5. Abstract Classes6. Interfaces7. The Comparable Interface

Page 2: Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes

Inheritance • Superclasses and Subclass– Inheritance defines a relationship between

objects that share characteristics. • Subclass – is created from an existing

superclass. • Subclass inherits charatceristics of its

superclass.• Subclass is bigger than a superclass – it

contains more data and more methods.• Allows you to reuse code over and over gain.

Page 3: Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes

Inheritance Hierarchy• Inheritance hierarchy – when a subclass

itself is a superclass for another subclass.

***Note Arrow points to its superclass

Person

Student Employee

GradStudent UnderGrad

Page 4: Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes

Is-a Relationship• Arrow designates an is-a relationship. • There needs to be an is-a relationship when working with inheritance.• Example:

– An Employee is-a Person– Student is-a Person– GradStudent is-a Student

• Opposite is not true– Person doesn’t always have to be an Employee

• The subclass inherits all public variables and methods of the superclass, but does not inherit the constructors even though they are public.

Page 5: Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes

Method Overriding• When the subclass and superclass has the

exact same method in each of their class. The subclass method will override the superclass method.

• To run the superclass method, you must use the keyword super which will be discussed later.

Page 6: Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes

extends Keyword• In the subclass, you must use the extends

keyword to inherit the superclass methods and variables.– Example:

public class Subclass extends Superclass{}

• You can only extend one class at a time• A Parent class (superclass) can have multiple

children classes (subclasses) but a child class can only have one parent class.

Page 7: Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes

Protected • There is a protected specifier along with

public and private• Not part of the AP Subset• All protected variables and methods are

inherited.

Page 8: Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes

Super keyword

• Subclass methods overrides superclass methods with the same method heading signatures. Super allows you to undo the override.

• By using super.methodName() allows you to run the method of the superclass over its subclass method.

Page 9: Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes

Super & Constructors• Constructors are never inherited• Be sure to provide at least one constructor

when you write a subclass. Constructors are never inherited from the superclass.

• If the superclass does not have a default constructor but does have a constructor with parameters, creating a subclass without constructors will cause an error.

• To run the constructor of the superclass, just use super() by itself.

Page 10: Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes

Super examplespublic GradStudent(){

super();myGradId = 12345;

}Examplepublic GradStudent(String name,String grade, int id){

super(name,grade);myGradId = id;

}If super is used in the implementation of a subclass constructor, it must be used in the first line of the constructor body.If no constructor is provided in a subclass, the compiler provides the following default constructor

public Subclass(){

super();}

Page 11: Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes

Rules for Subclasses• A subclass can add new private instance

variables• A subclass can add new public, private, and

static methods• A subclass can override inherited methods• A subclass may not redefine a public methods of

the superclass.• A subclass should define its own constructors• A subclass cannot directly access the private

members of its superclass. It must use accessor or mutator methods.

Page 12: Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes

Declaring Subclass Objects• When a variable of a superclass is declared

in a client program, that reference can refer not only to an object of the superclass, but also to objects of any of its subclasses. – Example:

Student s = new Student();Student g = new GradStudent();Student u = new UnderGrad();

• This works because a GradStudent is-a Student, and an UnderGrad is-a Student.

Page 13: Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes

Not Valid• Note that since a Student is not necessarily

a GradStudent nor an UnderGrad, the following declarations are not valid:– GradStudent g = new Student();– UnderGrad u = new Student();

Page 14: Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes

ExampleStudent s = new Student();Student g = new GradStudent();Student u = new UnderGrad();

• Suppose a method called setGrade() is in the Student class.

s.setGrade(“pass”); will work because it is in the Student class.g.setGrade(“pass”); & u.setGrade(“pass”); will work because inheritance.

Page 15: Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes

Bad calls• Suppose getID() is in the GradStudent class.

int studnum = s.getId();int unstudnum = u.getId();

• Neither Student s nor UnderGrad u inherit the getID() method from the GradStudent class.

• A superclass does not inherit from the subclass.

Page 16: Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes

PolymorphismStudent s = new Student();Student g = new GradStudent();Student u = new UnderGrad();

• The method computeGrade() is all classes (Student, GradStudent, UnderGrad)

• The following are legal because they all have been declared Student.

s.computeGrade();g.computeGrade();u.computeGrade();

• The question is which computeGrade() method will run.

Page 17: Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes

Polymorphism• A method that has been overridden in at least one

subclass is said to be polymorphic. • Polymorphism is the mechanism of selecting the

appropriate method for a particular object in a class hierarchy. Selected during runtime.

• The correct method is chosen because, in Java, method calls are always determined by the type of the actual object (GradStudent or UnderGrad), not the type of the object reference (Student).

• The previous slide computeGrade() will all perform the correct operations for their particular instances(Student, GradStudent, & UnderGrad objects s,g,u).

Page 18: Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes

Dynamic Binding (Late Binding)• Making a runtime decision about which instance method

to call is known as dynamic binding or late binding (method overriding).

• Static binding or early binding is done at compile time. (method overloading) compares method signatures.

• In polymorphism, the actual method that will be called is not determined by the compiler.

• Example:– The compiler determines if a method can be called(is it

legal?). While the run-time environment determines how it will be called(which overridden form should be used?).

• Polymorphism applies only to overridden methods in subclasses.

Page 19: Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes

Type Compatibility• Suppose method getId() only exist in the

GradStudent class.Student s = new GradStudent();GradStudent g = new GradStudent();int x = s.getId(); //ERRORint y = g.getId(); //Legal

• Both s and g represent GradStudent objects, so why does s.getId() cause an error??

• The reason is that s is of type Student, and the Student class doesn’t have a getId() method.

• Remember getId() method is only in UnderGrad and not Student so this is not Polymorphism because no method is being overridden.

Page 20: Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes

Downcasting• You can fix the other slide problem by

Downcasting.int x =((GradStudent)s).getId();• Since s (of type Student) is actually

representing a GradStudent object, such as a cast can be carried out. Casting a superclass to a subclass type is called Downcasting.

• Notice the parenthesis are necessary around the s. An Error would occur if lefty out.

• Dot operator has a higher precedence than a cast.

Page 21: Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes

Rules for Polymorphic Method Callsa.method(b)

• For a declaration like: Superclass a = new Subclass():

The type of a at compile tie is Superclass; at run time it is Subclass

• At compile time, method must be found in the class of a, that is, in Superclass. (this is true whether the method is polymorphic or not) If method cannot be found in the class of a, you need to do an explicit cast on a to its actual type.

• For a polymorphic method, at run time the actual type of a is determined – Subclass in this example – and method is selected from Subclass. This could be an inherited method if there is no overriding method.

• The type of parameter b is checked at compile time. You may need to do an explicit cast to the subclass type to make this correct.

Method selected by type of “a” at run time Parameter b must be of

correct type at compile type

Page 22: Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes

The ClassCastException• The ClassCastException is a run-time

exception thrown to signal an attempt to cast an object to a class of which it is not an instance.

• Examples:Student u = new UnderGrad(); System.out.println((String)u); //ClassCastException u is not a String

int x = ((GradStudent)u).getID();// ClassCastException u is not an //instance of GradStudent

Page 23: Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes

Abstract Classes• Abstract class are declared with keyword abstract

in the header.• An abstract class is a superclass that represents an

abstract concept, and therefore should not be instantiated.

• An abstract class may contain abstract methods. – An abstract method has no implementation code, just

a header and ends with a semicolon “;”– Every subclass will need to override the abstract

method of the Superclass.• If a class contains any abstract methods, it must be

declared an abstract class.

Page 24: Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes

Abstract Classes• If a subclass of an abstract class does not provide

implementation code for all the abstract methods of its superclass, it too becomes an abstract class and must be declared as such to avoid a compile-time error.

• An abstract class can have both abstract methods and concrete methods (nonabstract methods)

• It is possible for an abstract class to have no abstract methods

• Abstract class may or may not have constructors• You can not create an instance of an abstract class• Polymorphism works with abstract classes as it does

with concrete classes. (non abstract class)

Page 25: Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes

Interfaces• An interface is a collection of related methods whose headers are

provided without implementations. (simply put a class of all abstract methods)

• All of the methods are public and abstract – there is no need to explicitly include public and abstract keywords.

• Classes can implement the interface by using the keyword “implements”

• Example of interface class:public interface FlyingObjetcs{

void fly();Boolean isFlying();

}• Example on a class implementing an Interface

public class Bird implements FlyingObject

***Note: Class Bird must have the code for methods fly() & isFlying()

Page 26: Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes

implements Keyword• You can implement an Interface and extend

a class at the same time.Example:Public class Mosquito extends Insect implements FlyingObject

Notes:– The extends clause must precede the implements clause.– A class can have just one superclass, but it can implement any

number of interfaces:public class Subclass extends Superclass implements Interface1, Interface2 …

Page 27: Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes

Comparable Interface• java.lang package contains the Comparable interface,

which provides a useful method for comparing objects.

• Classes written for objects that need to be compared should implement Comparable.– Example:

public interface Comparable{

int compareTo(Object obj);

}***Note any class that implements Comparable must provide a compareTo method that returns a 0, negative or positive. If the objects being compared are not type compatible, a ClassCastException is thrown by the method

Page 28: Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes

Abstract Class vs Interface• Use an abstract class for an object that is

application specific, but incomplete without its subclasses.

• Consider using an interface when its methods are suitable for your program, but could be equally applicable in a variety of programs

• An interface cannot contain instance variables, whereas an abstract class can.

• An interface and an abstract class can both declare constants.

• It is not possible to create an instance of an interface object or an abstract class object