Lab07 Inheritance
Lab07 Inheritance
Lab 7
Content
• Inheritance
• Overriding methods
• Access modifiers
• Object class
2
Inheritance - Motivation
• Consider a transportation computer game
– Different types of vehicles:
• Planes
– Jets, helicopters, space shuttle
• Automobiles
– Cars, trucks, motorcycles
• Trains
– Diesel, electric, monorail
• Ships
– …
3
Inheritance - Motivation
• Sample code for the types of planes:
– takeOff()
– fly()
– setAltitude()
– land()
4
Inheritance - Motivation
• Indeed, all vehicles will have similar methods:
– move()
– getLocation()
– setSpeed()
– isBroken()
• What we want is a means to specify one move() method, and have each
vehicle type inherit that code
– Then, if we have to change it, we only have to change one copy
5
Inheritance - Motivation
Provides: Provides:
fly() move()
takeOff() getLocation()
land() setSpeed()
setAltitude() Vehicle isBroken()
Provides: Provides:
derail() oilChange()
getStation() isInTraffic()
6
Inheritance - Motivation
• What we will do is create a “parent” class and a “child” class
• The “child” class (or subclass) will inherit the methods (etc.) from
the “parent” class (or superclass)
• Note that some classes (such as Train) are both subclasses and
super classes
7
Inheritance - Motivation
□Child of Vehicle
□Parent of Diesel, Electric and Monorail
□ Parent Class
Vehicle
□ Child Class
8
Inheritance
• Inheritance is the process by which a new class is created from
another class
– The new class is called a derived class or subclass
– The original class is called the base class, parent class or superclass
• The subclass
– Will automatically inherit all methods and instance and static variables
from the superclass.
– Can declare more instance variables and methods
9
Inheritance code
□ Superclass
class Vehicle {
...
}
10
About extends
• If class A extends class B
– Then class A is the subclass of B
– Class B is the superclass of class A
– A “is a” B
– A has (almost) all the methods and variables that B has
11
Inheritance
• Organizes objects in a top-down fashion from most general to
least general
12
Inheritance
VEHICLE
13
Inheritance
VEHICLE
NUMBER
Passenger
14
Overriding
• Overriding is the process of changing the definition of an
inherited method
• Each time you write a class you may override the methods.
– equals(Object obj)
– toString()
15
Simple Example
• We can effectively model similar,
but different types of objects
using inheritance. PET
16
The Pet Class
class Pet {
private String name;
public String getName() {
return name;
}
public void setName(String petName) {
name = petName;
}
public String speak( ) {
return “I’m your cuddly little pet.”;
}
}
17
Sub-Class of the Pet Class
18
Sample Usage of the Subclasses
19
Overriding
• To override a method
– Create a method in the subclass with the same header as the method in
the parent class.
Pet
Cat
20
Do not confuse Overriding, Overloading
21
The final Modifier
• If the modifier final is placed before the definition of a method,
then that method may not be redefined in a derived class.
22
Self-Test (1)
• 프로젝트 명: Project07_1
– git commit –m “Project07_1”
23
Self-Test (1)
• Manager Class는 Employee Class를 extends한다.
– Manager Class에는 2개의 instance 변수가 있다.
• int officeNum
• String team
– 생성자는 정의되어 있다.
– Manager의 name과 employeeNum, location을 반환하는 toString() 메소드를 만든다.
이 때, location은 department 및 officeNum이다.
(형식 : Name : [name]\nlocation : [department], [officeNum])
24
Inheritance and Constructors
• Unlike members of a base class, constructors of a base class are
not inherited by its subclasses
25
Inheritance and Constructors
• super like the word this can be used to refer to different objects
in the hierarchy.
super
this
26
super Constructor
• To define a constructor using the superclass’s constructor
– add the super constructor as the first statement of the derived
constructor.
public Car(){
super();
this.number = 0;
}
27
this Constructor
• The this constructor refers to an overloaded constructor in the
same class.
– i.e. Within the definition of a constructor for a class, this can be used as
a name for invoking a constructor of the same class
class Car extends Automobiles {
private int number;
public Car(){
super(); If it is necessary to include a call to both
super.number = 1;
super and this, the call using this
}
must be made first, and then the constru
public Car(Number num){
ctor that is called must call super as its
this();
this.number = num; first action
}
}
28
The this Constructor
• Often, a no-argument constructor uses this to invoke an explicit-
value constructor
– No-argument constructor (invokes explicit-value constructor using this
and default arguments):
public ClassName() {
this(argument1, argument2);
}
29
Access Modifiers
• Private instance variables in a superclass are not accessible by
name in a subclass
– They can be accessed using accessors and mutators.
30
The Protected Modifier
• The modifier protected makes a variable or method visible and
accessible to
– the instances of the class
– Instances of subclasses of the class.
– Instances of classes in the same package
31
Packages
• Allow definitions to be collected together into a single entity — a
package.
• Classes and names in the same package are stored in the same
folder.
32
Controlling access
• Class access rights
public O O O O
protected O O O
default
no modifier O O
private O
33
Access Modifiers
34
Changing the Access Permission of an
Overridden Method
• The access permission of an overridden method can be changed
from private in the base class to public (or some other more
permissive access) in the derived class
35
Changing the Access Permission of an
Overridden Method
• Given the following method header in a base case:
– private void doSomething()
36
Object class
• Java contains a special class in the java.lang package known as
Object
• All classes in java are inherited from the Object class. This means
all classes are Objects.
37
Object class
• The class Object has some methods
that every Java class inherits Object
– equals(Object obj)
equals
– toString() toString()
38
Better equals Method
• The equals method is inherited from the Object class.
• When overriding the equals method it should accept an Object as the
parameter.
39
Better equals Method
40
The instanceof Operator
• The instanceof operator checks if an object is of the type given as
its second argument
41
The instanceof Operator
42
The getClass() Method
• Every object inherits the same getClass() method from the Object
class
– This method is marked final, so it cannot be overridden
(object1.getClass() == object2.getClass())
43
Object Class
• System.out.println()
– Out (static)
• System?
– java.lang
44
Self-Test (2)
• 프로젝트 명: Project07_2
– git commit –m “Project07_2”
– 당일 밤 12시까지 제출
• Employee Class를 수정한다.
– 이전에 작성했던 equals() 메소드를 equals(Object obj) 를 오버라이딩 하도
록 수정한다.
– employeeNum 변수에 대한 accessor/mutator 메소드를 추가한다.
• Manager Class를 수정한다.
– name과 employeeNum, officeNum, team을 인자로 받는 생성자를 작성한
다.
– Manager의 name, employeeNum, officeNum, team이 동일할 경우 true, 다
른 경우 false를 반환하는 equals(Object obj) 메소드를 작성한다.
(Super Class의 equals()를 사용한다.)
45
Self-Test (2)
• Employee Class를 extends하는 Engineer Class를 작성한다.
– Engineer Class는 2개의 instance 변수가 있다.
• String workZone, String project
– name, employeeNum, workZone, project을 인자로 받는 생성자를 작성한다.
– Engineer의 name, employeeNum, workZone이 동일하다면 true를, 다르다면 false를 반환하는
equals(Object obj) 메소드를 작성한다.
(Super Class의 equals()를 사용한다.)
– Engineer의 name, employeeNum, department, workZone을 반환하는 toString()을 작성한다.
(형식 : Name : [name]\nEmp# : [employeeNum]\nlocation : [department], [workZone])
46