Anda di halaman 1dari 14

Containment

Inheritance and
Polymorphism A class contains another class if it instantiates an
object of that class
This can be described as a “HAS-A” relationship
CSE 114: Computer Science I
Course HAS-A Professor
Stony Brook University
CAR HAS-A Engine

UML Class Diagrams Method and Instance Variable Descriptions


• Derived from class responsibilities diagrams
• Show relationships between classes • Instance Variables Format
– Class associations denoted by lines connecting classes – variableName : variableType
– A feathered arrow denotes a one-directional association – For example,
Connecting line means ClassA and upValue : int
ClassB know of and use each other • Method Header Format
ClassA ClassB – methodName(argumentName :
Instance variable info Instance variable info
argumentType): returnType
Method header info Method header info
– For example,
setDie1(newDie1 : Die) : void
Feathered arrow means ClassA
ClassC knows of and uses ClassC, but
Instance variable info ClassC has no knowledge of
Method header info ClassA
UML Class Diagrams & Containment Class Diagrams and Encapsulation
• UML class diagram for PairOfDice & Die: • In a UML class diagram
Diamond denotes containment
– public members can be preceded by a plus sign
PairOfDice HAS-A Die
– private members are preceded by a minus sign
PairOfDice Die
PairOfDice Die
numFaces: int
die1: Die 1 2 upValue : int - die1: Die - numFaces: int
die2: Die - upValue : int
- die2: Die
getDie1() : Die getUpValue() : int
getDie2() : Die getNumFaces() : int + getDie1() : Die + getUpValue() : int
getTotal() : int roll() : void + getDie2() : Die + getNumFaces() : int
rollDice() : void + getTotal() : int + roll() : void
setDie1(newDie1: Die) : void + rollDice() : void
setDie2(newDie2: Die) : void Denote multiplicity, 2 + setDie1(newDie1: Die) : void
+ setDie2(newDie2: Die) : void
Die object for each
PairOfDice object

Cats and Dogs Cats and Dogs


Cat Dog

Is a mammal Is a mammal
Some classes share properties that are similar
Has fur Has fur
For example, cats and dogs are both mammals and
Common house pet Common house pet common house pets
Has several breeds Has several breeds It doesn’t make sense to duplicate shared
properties unnecessarily (remember the DRY
principle we discussed previously)
Meows Barks

Scratches the furniture Catches Frisbees Instead, we can abstract out common
characteristics
Catches mice Chases squirrels

Can guard a house


Cats and Dogs Inheritance

Inheritance A mechanism by which one class


acquires (inherits) the properties (both data fields
and methods) of another class.
Superclass The class being inherited from
Derived class The class that inherits
The derived class is specialized by adding
properties specific to it

10

Inheritance Why use Inheritance?


An object class that is derived from another class Customize classes (from the JDK or your own)
inherits its instance variables and methods
Benefits:
child class parent class
Don’t have to re-write code
“IS–A”
Use methods and variables from fully tested classes
subclass superclass
Superclass code can be used in any number of
derived class base class subclasses
An instance variable or method that is inherited by Changing common properties is easy – just change
a subclass does NOT need to be redefined the parent class
Inheritance Syntax Sample Inheritance Code
public class Mammal
{
public class ChildClass extends ParentClass boolean hasFur = true;
public void makeSound(){}
{ }

// instance variables for Child only public class Cat extends Mammal
{
// methods for Child only boolean hasClaws;
String furColor;
} public void makeSound()
{
ChildClass now contains all instance variables and System.out.println(“Meow!”);
methods defined above, as well as those defined inside }
ParentClass }

Sample Inheritance Code II Organizing classes with Inheritance


public class Persian extends Cat Determine what data you need to store. For example, for
{ storing student and employee data:
String furColor = “White”;
Student data: name, age, GPA
public void makeSound() Employee data: name, age, salary
{
System.out.println(“Hisss!”); Divide up your classes by state – Students and Employees
} store different data, so make them into separate classes
}
Pool common data into a common parent class
• Persian inherits hasClaws from Cat.
• Persian overrides Cat’s makeSound() method. Person data: name, age
• Persian hides Cat’s furColor field. Have Student and Employee customize Person
Example: Example: Child (Sub-)Class: Student
public class Person
{ private String name; Parent Class: Person public class Student extends Person Means Student
private int age; { private double gpa; inherits all instance
variables and methods
// constructor for a Person from Person
public Person(String initName) // constructor for a Student
{ age = 0; // just born public Student(String initName)
name = initName; }
{ super(initName); Runs Person’s
// accessor method to get Person's name
gpa = 0.0; } constructor
public String getName() { return name; }
public double getGpa() { return gpa; }
// accessor method to get Person's age
public int getAge() { return age; }
public void setGpa(double newGpa)
// mutator method to set person's age { if (newGpa < 0.0 || newGpa > 4.0)
public void setAge(int newAge)
gpa = 0.0;
{ if (newAge < 0) age = 0;
else age = newAge; else

} gpa = newGpa; }
} }

Example: Child (Sub-)Class: Employee Example: Using all three classes


public class Employee extends Person public class PeopleTester
{ { public static void main(String[] args)
private int salary; { Person moe = new Person("Moe Stooge");
Student larry = new Student("Larry Stooge");
// constructor for an Employee Employee curly = new Employee("Curly Stooge");
public Employee(String initName)
{ super(initName); moe.setAge(106); // LEGAL? YES!
salary = 0; moe.setGpa(2.2); // LEGAL? NO!
} moe.setSalary(100000); // LEGAL? NO!

public int getSalary() { return salary; } larry.setAge(101); // LEGAL? YES!


larry.setGpa(1.2); // LEGAL? YES!
public void setSalary(int newSalary) larry.setSalary(50000); // LEGAL? NO!
{ if (newSalary < 0 || newSalary > 400000)
salary = 0; curly.setAge(100); // LEGAL? YES!
else curly.setGpa(0.5); // LEGAL? NO!
salary = newSalary; } curly.setSalary(25000); // LEGAL? YES!
} }
}
Inheritance: public vs. private
• Inherited methods are accessible by the derived class if
Four Levels of Class Member Access
they are public or protected.
• Inherited instance variables are not directly accessible by
the derived class if they are private.
– Use public accessor/mutator methods of parent class instead.
– For example, if we added a clear method inside Student: public
protected
public void clear() public void clear()
package
{ age = 0; { setAge(0); private
gpa = 0.0; gpa = 0.0;
} }

ILLEGAL LEGAL
• private methods of a base class are not accessible by
the derived class. 22

Inheritance: super() and this()


Member Accessibility • super() runs base (parent) class' constructor
– Must be first statement in a derived class' constructor
External access public protected (default) private – If it is left out, super() is still executed using the base class'
package
default constructor (with no parameters)
• this() runs a class' own constructor
Same package yes yes yes no – Used on first line of another constructor
– May pass parameters to this() as long as they correspond to
parameters for another constructor
Derived class in yes yes no no – For example, if we added a new constructor for Student:
another package (inheritance
public Student(String initName, double initGpa)
only)
{
this(initName); Runs the previously
User code yes no no no
gpa = initGpa; defined Student
} constructor
23
More Definitions public class Example
{
char letter;
public static String lineIs();
Override When an instance method in a derived class has …
the same form of heading as an instance method in its }
superclass, the method in the derived class overrides
(redefines) the method in the superclass
Hide When a field in a derived class has the same name as public class ExtExample extends Example
one in its superclass or a class method has the same form {
of heading as a class method in its superclass, the field or char letter;
class hide the corresponding component in the superclass public static String lineIs();

Say again?
}
Hiding or overriding?

public class Example


{
 Overriding vs. Hiding
char letter;

public String lineIs();


}
We override an instance method of a superclass by
public class ExtExample extends Example providing an instance method in a derived class with the
{ same form of heading
String letter;
public String lineIs();

} We hide a data field of a superclass by providing a field in
a derived class with the same name
Hiding or overriding?
28
Inheritance: Overriding Methods The Object class
• A method is overridden if it is redefined in a derived class
(child class) using the same method signature. • Every class is a subclass of the java.lang.Object
class, even if not specified directly.
• Person (parent class):
Method Summary
public void reset() protected clone() 

{ age = 0; } Object Creates and returns a copy of this object.
• Student (child class):  boolean equals(Object obj) 

Indicates whether some other object is "equal to" this one.
public void reset()
{ setAge(0);  String toString() 

Returns a string representation of the object.
gpa = 0.0; }
– OR, Calling an overridden method: Automatically called on an object whenever it is
placed inside System.out.print(…
public void reset()
{ super.reset(); What happens if • The 3 methods above are overridden nearly every time a
you forget super? new class is defined.
gpa = 0.0;
 • The Object class also contains 8 other methods we
} won’t use

Overriding toString() method Example Printing using toString()


public class StoogePrinter
public class Person
{ … {
public String toString() public static void main(String[] args)
{ return name + ", age " + age; } {
} Person moe = new Person("Moe Stooge");
Student larry = new Student("Larry Stooge");
public class Student extends Person Employee curly = new Employee("Curly Stooge");
{ …
public String toString() System.out.println(moe.toString());
{ return super.toString() + ", GPA: " + gpa; } System.out.println(larry.toString());
} System.out.println(curly);
}
public class Employee extends Person }
{ … OUTPUT: Moe Stooge, age 0
public String toString() Larry Stooge, age 0, GPA: 0.0
{ return super.toString() + ", Salary: $" + salary; }
Curly Stooge, age 0, Salary: $0
}
public class Course
Multiple Inheritance?
{ public int courseNumber = 114; } Exercise to try • A class may extend only 1 class, however, when it does so it also inherits all
methods and variables that the parent class has already inherited
public class Classroom at home • Example:
{ public String building = "Javits"; public class Instructor extends Employee
public int roomNumber = 100; { private String dept;
public String toString()
{ return building + roomNumber; } public Instructor(String initName)
{ super(initName); dept = "None Assigned"; }
}
public String getDept() { return dept; }
public class LectureHall extends Classroom public void setDept(String newDept) { dept = newDept; }
{ public int capacity = 650; }
public String toString()
public class ToStringExample { return super.toString() + ", Dept: " + dept; }
{ public static void main(String[] args)
{ public static void main(String[] args)
System.out.println(new Course()); { Instructor me = new Instructor("Richard McKenna");
System.out.println(me); }
System.out.println(new Classroom());
}
System.out.println(new LectureHall());
OUTPUT:
}
What output do you get? Richard McKenna, age 0, Salary: $0, Dept: None Assigned
}

Inheritance Diagrams Inheritance Diagrams – family tree?


• Think of an inheritance diagram as a family tree The Town Mama

for classes, except for a couple of differences: Drunk

– A class may only have 1 immediate parent


Uncle Mary Joe Farmer’s
– No criss-crossing in a class tree Ernie Joe Bob
daughter across
state line

– Every class has all the properties (state and behavior)


of all of its ancestors (so much for Darwinism) Old Man Up
the
Elvira Fat Little
Mountain Irma Bob

Person
• A class may have any Cletus Mary
number of ancestors; Joe

Student Employee in this case, Danger: The


Instructor has 2. Elvis Selma
family tree is
Sue crossing!
Instructor
Inheritance Diagram Example UML Class Diagrams & Inheritance
• A class may only have public class Student extends Person
Object 1 immediate parent
Person
• No criss-crossing in a
name: String
Component class tree age : int

getAge() : int
Container getName() : String
setAge(newAge: int) : void
Triangle denotes inheritance
JComponent Window
Student IS-A Person

Student
JPanel AbstractButton Frame
gpa: double

getGPA() : double
JFrame setGPA(newGPA: double) : void
JButton

Cats and Dogs (yes, again) Cats and Dogs Revisited


public class Cat extends Mammal
{ ...
public void makeSound()

{
System.out.println(“Meow!”);
}
}

Public class Dog extends Mammal


{ ...
public void makeSound()

{
System.out.println(“Woof!”);
}
}
Cats and Dogs Revisited (II) Polymorphism
Cat garfield = new Cat();
Dog odie = new Dog();
Polymorphism is the ability of a language to have
garfield.makeSound(); duplicate method names in an inheritance hierarchy
odie.makeSound(); and to decide which method is appropriate to call
depending on the class of the object to which the
Mammal m = new Cat(); method is applied.
m.makeSound();

What does each call to makeSound() produce?


42

OOP Characteristics
Assignment

Characteristic Meaning Benefit


We can always assign a derived class to any
New classes created Software parent class variable
Inheritance from existing classes reusability
the derived class IS-A parent object
Mammal m = new Cat();
Write programs to handle Add new Cat satisfies all of Mammal’s criteria, and
Polymorphism a variety of existing and capabilities
future related classes it also includes Cat-specific features

43
Assignment Method Invocation
Suppose that Mammal and Cat each define a
We CANNOT go the other way, though! method named makeSound()
Cat c = new Mammal(); // Illegal Cat’s version overrides Mammal’s version
c expects to point to an object with all of Cat’s Which version of makeSound() will be called in
features each of the following cases?
There is no guarantee that a Mammal object has 1. Mammal m = new Mammal();

all of those features m.makeSound();
In fact, it probably doesn’t 2. Mammal x = new Cat();

x.makeSound();

Basic Rules Examples

Every variable has two types:


Mammal m = new Mammal();
its reference type
Reference and actual types are both Mammal
its actual type
Mammal x = new Cat();
The reference type determines what methods
can be called Reference type: Mammal
The actual type determines which versions of Actual type: Cat
those methods are called
Abstract Classes
Polymorphism
• Classes with instance variables & defined methods
that are not meant to be instantiated
Polymorphism means that you can send the – Instead, they exist to be extended
same message to different objects – Subclasses would then have constructors
Inheritance means that objects share the same • This is a means for combining useful properties
code and functionality together into an incomplete class
definition
Results may vary depending upon the specific
object involved – Someone can create their own class, extending the
abstract class, and thus save on coding
Cat (probably) responds differently from Dog
• Use the abstract keyword
– ex. abstract class Foo { ... }

Another Type of Inheritance Interfaces


A Java interface allows classes to share
common behavior (but not actual code)
Inheritance (in general) specifies IS-A relationships
inheritance shares CODE as well as behavior
e.g., Cat IS-A Mammal
If a class implements an interface, it promises to
A class can only inherit directly from one class define all of that interface’s methods (along with its
own instance and/or class variables and methods)
What if you want a class to share the behavior of
several classes? Polymorphism applies to interfaces as well; a
method parameter can refer to an interface rather
than a specific class type
Defining Interfaces Using Interfaces

Use the implements keyword to indicate that a


class conforms to a particular Java interface

public interface Comparable
 Separate multiple interface names with commas:



{
 

public int compareTo(Object o);
 class A implements B, C
} You must provide method bodies for every
method listed in each interface that you implement
This is in addition to any class-specific methods

Putting It All Together


public class Foo implements Comparable

{
 A class can simultaneously extend (one) class and
... implement multiple interfaces:

public class Cola extends Beverage


public int compareTo(Object o)
 implements Carbonated, Caffeinated
{
 {
...
 // Cola variables and methods
}
// Carbonated interface methods
} // Caffeinated interface methods
}

Anda mungkin juga menyukai