!
" !
Supplementary Objectives
$ #
# #
%
&&'(
$ this() super()
# #
) %
* (# instanceof
$ !
+ - # , % #
( % ./# /00( +
+
% , , ! super(#
# #
% ./# /00( +
% 1, .2(
extends
+ extends
# java.lang.Object
Light %
2( 1, .2 3 1,
.2# TubeLight %
/( , extends
Light % # #
Object ( 4 Light
TubeLight#
'
indicator Light # ,
$ #
# # % 56# 207( 3 1,
.2#
private 4
! ! #
!
// Static fields
private static int counter; // no. of Light objects created
// Constructor
Light() {
noOfWatts = 50;
indicator = true;
location = "X";
counter++;
}
// Instance methods
public void switchOn() { indicator = true; }
public void switchOff() { indicator = false; }
public boolean isOn() { return indicator; }
private void printLocation() {
System.out.println("Location: " + location);
}
// Static methods
public static void writeCount() {
class TubeLight extends Light { // (2) Subclass uses the extends clause.
// Instance fields
private int tubeLength = 54;
private int colorNo = 10;
// Instance methods
public int getTubeLength() { return tubeLength; }
& :
Tube length: 54
Color number: 10
Wattage: 50
Indicator: true
Location: X
Number of lights: 1
3 - , " #
!
#
% (
; #
; # 8
< .2
Light# # 8
java.lang.Object - #
# , Object # % (
+ % (
+ = 3 TubeLight
Light 3 TubeLight
Light : B ,
A, C# , B# A B 3
SpotLightBulb Light
: LightBulb TubeLight
#
% ! (
% ! 3 Light :
%
noOfWatts(# %
indicator(# String
% location( + - #
+
;
+ .9
, &&' # =
& :
! String Object
Upcasting
3
#
% ..# /.>( + 1, ./# %5(#
stringRef objRef
String &
! , String objRef#
%
?(
@ # ! ! objRef
+ ! 3 Object
length()# length() %
?(
Method Overriding
+ %
?(# equals() %
.(
objRef ! Object
equals
A String % #
( % ./#
/00(
equals() %
.(# objRef,
! equals() Object !
!
.7
!
$ , # objRef String
%
.(# equals() String , #
Object
%
7(# getClass() !
objRef# Object getClass
+ # , # objRef
String %
7( ) !
getClass() getClass() String #
getClass() Object ,
Downcasting
; %
..# /.>( 1, ./
# = ,
3 %
9(# objRef Object#
stringRef + objRef
String # #
stringRef %9( stringRef
! equals() String # %
6( A # equals()
String ,
,
@ # +# #
objRef Object
Object# String +
# ClassCastException instanceof %
..# /.5(
Review Questions
+ - extends
abstract abstract
3 final abstract
3 private#
public
1 - public equals
1 - public length
3 ,
3 final ,
% #
(
final
% 0//# 65( 3 * final
#
#
% 56# 207(
# ,
% ( throws
% ?6# />2(
= #
% .5# /?2(
" #$ %#$ %
// Exceptions
class InvalidHoursException extends Exception {}
class NegativeHoursException extends InvalidHoursException {}
class ZeroHoursException extends InvalidHoursException {}
class Light {
public static String billType = "Large bill"; // (4) Hiding static field.
return largeBill;
}
& :
3 ! super !
% /09(
3 static
3 #
! @ #
static % (
3 final final 3
final @ # abstract
= #
3 private
" # @ #
#
Field Hiding
3 #
+ #
" #
; ! super #
3
# , & # #
!
! #
" # #
, + 1, .0 %
2/(#%
20(# %
25(#
! getBill():
, #
# #
# + 1,
.0 %
2?(#%
2.(# %
27(# billType:
#
+ #
billType static #
#
= #throws # +
# #
+ %
29( TubeLight# #
printBillType() %
.( ! + %
26( %/>( Light
printBillType() %
0( !
3 # # !
3 # ! super
! % /09(
3 + !
= ,% # !
super( !
+ ! #
! + 1, .0# getBill() %
/(
Light TubeLight %?( %
7( !
%
/2(# %
7( ,
1, .5
testIfOn() %
2( %/(
OverloadResolution client.testIfOn(tubeLight) %
0(
%
2( %/(# tubeLight#
TubeLight# Light
#%/(# # false
client.testIfOn(light) %
5(
%2(# true
& #$ '
}
}
& :
false
true
+ 1, .?# demonstrate() %
6( NeonLight ! super
!
banner() ! %2>( %
5( Light
NeonLight getBill()
%
.( %
9( TubeLight ! # super %
2/( %
22(#
3 %
25( ! super billType %
?( TubeLight 3 %
2?(
billType Light this #
<
# #
this @ # this !
#
getBill()
< # %
2.( %
27( super this #,
() super * !
// Exceptions
class InvalidHoursException extends Exception {}
class NegativeHoursException extends InvalidHoursException {}
class ZeroHoursException extends InvalidHoursException {}
class Light {
public static String billType = "Large bill"; // (5) Hiding static field.
& :
Review Questions
" B
& C # B
// Classes
class Foo {
private int i;
public void f() { /* ... */ }
public void g() { /* ... */ }
}
// Declarations:
// ...
Foo a = new Foo();
Bar b = new Bar();
// ...
Bar Foo
b.f();
a.j = 5;
a.g();
b.i = 3;
( B
'
3 ,
C A#B# C# B , A# C , B#
void doIt() @ doIt() A
CB
doIt();
super.doIt();
super.super.doIt();
this.super.doIt();
A.this.doIt();
+ ((A) this).doIt();
, B
// Filename: MyClass.java
public class MyClass {
public static void main(String[] args) {
C c = new C();
System.out.println(c.max(13, 29));
}
}
class A {
int max(int x, int y) { if (x>y) return x; else return y; }
}
class B extends A{
int max(int x, int y) { return super.max(y, x) - 10; }
}
class C extends B {
int max(int x, int y) { return super.max(x+10, y+10); }
}
max() B
super.max(y, x)
max()
13
23
29
+ 39
- C #
print() B
// Filename: MyClass.java
public class MyClass extends MySuperclass {
public static void main(String[] args) {
MyClass object = new MyClass();
object.print();
}
public void print() {
// INSERT CODE HERE THAT WILL PRINT
// THE "Hello, world!" STRING FROM THE Message
// CLASS.
}
}
class MySuperclass {
Message msg = new Message();
}
class Message {
// The message that should be printed:
String text = "Hello, world!";
}
System.out.println(text);
System.out.println(Message.text);
System.out.println(msg.text);
System.out.println(object.msg.text);
System.out.println(super.msg.text);
+ System.out.println(object.super.msg.text);
; #
#
+ 1, ..# Light
+ %0(# this
+ main() %5(#
! #
#$
class Light {
// Fields
private int noOfWatts; // wattage
private boolean indicator; // on or off
private String location; // placement
// Constructors
Light() { // (1) Explicit default constructor
noOfWatts = 0;
indicator = false;
location = "X";
System.out.println("Returning from default constructor no. 1.");
}
Light(int watts, boolean onOffState) { // (2) Non-default
noOfWatts = watts;
indicator = onOffState;
location = "X";
System.out.println("Returning from non-default constructor no. 2.");
}
Light(int noOfWatts, boolean indicator, String location) { // (3) Non-default
this.noOfWatts = noOfWatts;
this.indicator = indicator;
this.location = location;
System.out.println("Returning from non-default constructor no. 3.");
}
}
& :
1, .7 this() #
%
2(
%
/( 1, .. this() this()
# % ( #
%
2( %
/( this() !
+ main() %
5(# !
Light
; Light
,
+ #
# #
# !
" #
this(0, false)#
this(watt, ind, "X")# ,
# Light
,
- = this() this()
- *
,
,
, this()
class Light {
// Fields
private int noOfWatts;
private boolean indicator;
private String location;
// Constructors
Light() { // (1) Explicit default constructor
this(0, false);
System.out.println("Returning from default constructor no. 1.");
}
Light(int watt, boolean ind) { // (2) Non-default
this(watt, ind, "X");
System.out.println("Returning from non-default constructor no. 2.");
}
Light(int noOfWatts, boolean indicator, String location) { // (3) Non-default
this.noOfWatts = noOfWatts;
this.indicator = indicator;
this.location = location;
System.out.println("Returning from non-default constructor no. 3.");
}
}
}
}
& :
3 * % #
( ! super
& super !
@ # super() #
8
+ 1, .9# %
0( Light super() %
( %5( 3 # D
, D , %
.(
TubeLight super() % ( %
7( super()
%0( Light
- super()
class Light {
// Fields
private int noOfWatts;
private boolean indicator;
private String location;
// Constructors
Light() { // (1) Explicit default constructor
this(0, false);
System.out.println(
"Returning from default constructor no. 1 in class Light");
}
Light(int watt, boolean ind) { // (2) Non-default
this(watt, ind, "X");
System.out.println(
"Returning from non-default constructor no. 2 in class Light");
}
& :
# #
# Object A
, # super()
Object
#
% E (
1, .9 TubeLight
+ this() % this()
! ( , super()# super() % (
! + #
this() super() # super()
class A {
public A() {}
// ...
}
class B extends A {
// no constructors
// ...
}
class A {
public A() { super(); } // (1)
// ...
}
class B extends A {
public B() { super(); } // (2)
// ...
}
+ % # (#
super()
, # super()
NeonLight() { // (1)
super(10, 2, 100, true, "Roof-top"); // (2) Cannot be commented out.
sign = "All will be revealed!";
}
// ...
}
NeonLight %
2( %
/(
TubeLight + #
super() % (
TubeLight# TubeLight
NeonLight , super()
% ( %
/(
+ % # (#
3
, 3 ,
super() # # !
super()
Review Questions
. C # MySubclass
B
class MySuper {
int number;
MySuper(int i) { number = i; }
}
MySub() {}
/ B
3 super() this() ,
+ #
super()
+ super() this()
# this()
+ super() # this()
; super()
!#
// Filename: MyClass.java
public class MyClass {
public static void main(String[] args) {
B b = new B("Test");
}
}
class A {
A() { this("1", "2"); }
A(String s) { System.out.println(s); }
}
class B extends A {
B(String s) { System.out.println(s); }
B() { super("4"); };
}
+ Test
+ Test Test
+ 123 Test
+ 12 Test
+ 4 Test
6.4 Interfaces
1, 3
# #
# + - #
#
Defining Interfaces
3 ,:
# $ interface # $
# $ // Interface header
{ // Interface body
# $
# $
# $
# $
}
+ # ! interface +
# :
% 57# 202(
% .5# /?5(
% .5# /??(
% .5# /?5(
% 72# /95(
3 # #abstract
#
) abstract
# public
public
+
- 3'+ ,
! : java.lang.Cloneable#java.io.Serializable#
java.util.EventListener
3 #
abstract public 3
, abstract % 52># 257(
@ # abstract public #
F GF G (F G) F G;
1, .6 :IStack %
2( ISafeStack %
?(
=
. +
safeStackRef.push("Dollars"); // (10)
stackRef.push("Kroner");
System.out.println(isafeStackRef.pop());
System.out.println(istackRef.pop());
System.out.println(objRef.getClass());
}
}
& :
Kroner
Dollars
class SafeStackImpl
Implementing Interfaces
3 # #8 3
= implements
public
% ( 3
, * throws #
* #
3 #
, implements
3 #% #
( abstract % 59#
205( A static#
" +
, % (
; # ;
@ #
#
Extending Interfaces
3 , # extends $ ! , #
, , %
(# ; #
#
3 #
public 3
& 4
#
1, .6 , - + 1, .6#
ISafeStack , IStack %?( SafeStackImpl ,
StackImpl ISafeStack %
.(
1, .6
< .0
"
+ $4 # &
% & < .0 +
# ! #
- Object Object
< .0 ,
+ SafeStackImpl ISafeStack :
push() pop() StackImpl#
isFull() isEmpty() ISafeStack
ISafeStack IStack 3
SafeStackImpl SafeStackImpl
IStack : ISafeStack
IStack
< .0 SafeStackImpl
A !
:
: ,
% E (
4 : ,
% E (
" 4 :
3 #
H * + 1,
.6# SafeStackImpl main() StackUser
%
6( * #
'
.7
Constants in Interfaces
3
public#static final
8 8 , % 9/#
002(
3 % ( =
# , @ #
, #
=
1, .2>#
= %
2( %
/(#
1, ,
+ # +
# =
/0 +
interface Constants {
double PI_APPROXIMATION = 3.14;
String AREA_UNITS = " sq.cm.";
String LENGTH_UNITS = " cm.";
}
& :
Review Questions
+ ,
+ ,
4 static
" B
int answer;
& B
! extends
! extends
! implements
! implements
! implements
( B
// Filename: MyClass.java
abstract class MyClass implements Interface1, Interface2 {
public void f() { }
public void g() { }
}
interface Interface1 {
int VAL_A = 1;
int VAL_B = 2;
void f();
void g();
}
interface Interface2 {
int VAL_B = 3;
int VAL_C = 4;
void g();
void h();
}
void g() # #
int VAL_B # #
A #
C #
B
interface MyConstants {
int r = 42;
int s = 69;
// INSERT CODE HERE
}
1 1 0
1 0
' '
; # # % ( H
3 - 3 %
boolean[]#Object[]#StackImpl[](
< .0
< .5 3
I I []
SafeStackImpl StackImpl #
SafeStackImpl[] StackImpl[]# # #
< .5
& + 1
' Object # #
#
3 Object[]#
A Object[] Object
+ #
# %
abstract ( + # iSafeStackArray
ISafeStack[]#% # ISafeStack( ,
ISafeStack
ISafeStack 8
:
3 , ! #
% .7# /7/( @ # !
# ,
# %
StackImpl[](
%
SafeStackImpl[](:
StackImpl SafeStackImpl# :
%
/( SafeStackImpl SafeStackImpl[] % #
SafeStackImpl( %
2(
stackImplArray[i]#%
0 i < 2(# StackImpl#
:
3 #
stackImplArray SafeStackImpl[] @ #
%0( ArrayStoreException # SafeStackImpl
[] StackImpl
#
= ,
% (#
= , % ( + #
# = ,
2 + 0
// Parameter Conversion
System.out.println("First call:");
sendParams(stackRef, safeStackRef, iStackRef,
safeStackArray, iSafeStackArray); // (15)
// Call Signature: sendParams(StackImpl, SafeStackImpl, IStack,
// SafeStackImpl[], ISafeStack[]);
System.out.println("Second call:");
sendParams(iSafeStackArray, stackRef, iSafeStackRef,
stackArray, safeStackArray); // (16)
// Call Signature: sendParams(ISafeStack[], StackImpl, ISafeStack,
// StackImpl[], SafeStackImpl[]);
}
System.out.println(iStackArrayParam.getClass());
}
}
& :
First call:
class SafeStackImpl
class SafeStackImpl
class SafeStackImpl
class [LSafeStackImpl;
class [LSafeStackImpl;
Second call:
class [LSafeStackImpl;
class SafeStackImpl
class SafeStackImpl
class [LSafeStackImpl;
class [LSafeStackImpl;
# :
SourceType srcRef;
// srcRef is appropriately initialized.
DestinationType destRef = srcRef;
+ # srcRef %
( DestinationType
1, .22
+ SourceType # srcRef
destRef # DestinationType :
DestinationType SourceType
DestinationType SourceType
+ SourceType # srcRef
destRef # DestinationType :
DestinationType Object
DestinationType SourceType
+ SourceType # srcRef
destRef # DestinationType :
DestinationType Object
DestinationType # SourceType
DestinationType
% !
( % !
(
# - % 026# 96(# =
+ 1, .22# sendParams() %
27( #
:
%
2?( # :
A
# %
2.(
, + :
3 #
1, .22
#
SafeStackImpl SafeStackImpl[] [L
% Class.getName() 3'+
(
java.util ! ! Object
# %
; 22(
, # $ # $ # $
,:
(# $) # $
3 , ! # $
# $# # # $
# $ + # ClassCastException null
instanceof ,% !
(:
# $ instanceof # $
instanceof true %
# $(
%
# $(# false null
+ instanceof true# ,
instanceof = !
! ,
! # $
# $
# $ # $ + #
# instanceof
3 # # $
# $ #
$ Light String# #
# $ # $
Light String instanceof #
%/( %0( 1, .2/ # $ # $
Light TubeLight# # Light TubeLight
TubeLight % ( < .0 #
! instanceof Light TubeLight
%5( %?(# # 1, .2/
3 # instanceof %
5( false
light1 Light LightBulb,
TubeLight 3 %
?(
ClassCastException
# ClassCastException A
instanceof false#
ClassCastException
+ 1, .2/# instanceof %
.( false#
light1 LightBulb#
SpotLightBulb %
7(
ClassCastException
%
9(#%
6(# %
2>( instanceof
light1 Light 8
NeonLight %
9( instanceof %
6( true#
light1 NeonLight#
TubeLight ! # %
2>( +
instanceof true#
instanceof #
3 # instanceof
A
3 #
+ #
#
1, .20 , instanceof +
null
# %
2(#%
/(# %2.( 3
# %
5( 3
# %
2>( 3
#
%
.( 3 Object Object[] #
%
25( %
2?(#
") instanceof #
& :
(1): false
(2): false
(3): true
(4): false
(5): true
(6): false
(7): true
(8): true
(9): true
(10): false
(11): true
(12): true
(14): true
(15): true
(16): false
(17): true
Review Questions
, C # B
// Filename: MyClass.java
public class MyClass {
public static void main(String[] args) {
A[] arrA;
B[] arrB;
class A {}
class B extends A {}
%
2(
java.lang.ClassCastException
%
/(
java.lang.ClassCastException
%
0(
# (B[])
%
/( %
0(
# (B[])
%
/( %
0(
- B
// Filename: MyClass.java
class MyClass {
public static void main(String[] args) {
MyClass a;
MySubclass b;
a = b; // (3)
b = a; // (4)
%
2(
%
/(
%
0(
%
5(
%
?(
+ %
.(
. C #
B
// Definitions:
interface I1 {}
interface I2 {}
class C1 implements I1 {}
class C2 implements I2 {}
class C3 extends C1 implements I2 {}
// Reference declarations:
// ...
C1 obj1;
C2 obj2;
C3 obj3;
// ...
obj2 = obj1;
obj3 = obj1;
obj3 = obj2;
I1 a = obj2;
I1 b = obj3;
+ I2 c = obj1;
/ C #
y = (Sub) xB
// Class definitions:
class Super {}
class Sub extends Super {}
// Reference declarations
// ...
Super x;
Sub y;
// ...
) # (Sub)
) # (Sub)
C #
B
// Definitions:
interface A {}
class B {}
class C extends B implements A {}
class D implements A {}
// Declaration statements:
// [...]
B b = new B();
C c = new C();
D d = new D();
// [...]
c = d;
d = c;
A a = d;
d = (D) c;
c = b;
// Filename: MyClass.java
public class MyClass {
public static void main(String[] args) {
B b = new C();
A a = b;
if (a instanceof A) System.out.println("A");
if (a instanceof B) System.out.println("B");
if (a instanceof C) System.out.println("C");
if (a instanceof D) System.out.println("D");
}
}
class A {}
class B extends A {}
class C extends B {}
class D extends C {}
" C A#B# C# B A C B#
, true o
B A CB
(o instanceof B)
& # I#J#C, D +
B
interface I{}
interface J{}
class C implements I {}
class D extends C implements J {}
<
private ! #
,
) !
# @ # private
#
private
< .? 1, .25
draw() Shape
draw() %
0( %5( 1, .25#
! shapes Shape
Circle# Rectangle Square# %
2( 3 #
! draw() , #
drawables %
/(#
IDrawable
IDrawable !
Shape shapes + draw() #
,
drawables# IDrawable
( 2 '
' !
# #
&2 3 ' 4 5
interface IDrawable {
void draw();
}
System.out.println("Draw shapes:");
for (int i = 0; i < shapes.length; i++) // (3)
shapes[i].draw();
System.out.println("Draw drawables:");
for (int i = 0; i < drawables.length; i++) // (4)
drawables[i].draw();
}
}
& :
Draw shapes:
Drawing a Circle.
Drawing a Rectangle.
Drawing a Square.
Draw drawables:
Drawing a Shape.
Drawing a Rectangle.
Drawing a Map.
Review Questions
( B
# ClassCastException
class A {
private int f() { return 0; }
public int g() { return 3; }
}
class B extends A {
private int f() { return 1; }
public int g() { return f(); }
}
class C extends B {
public int f() { return 2; }
}
&
1 ! *
=
1 , #
#
( 3 6
// Methods
public void setData(Object obj) { data = obj; }
public Object getData() { return data; }
public void setNext(Node node) { next = node; }
public Node getNext() { return next; }
}
// Methods
public boolean isEmpty() { return head == null; }
public void insertInFront(Object dataObj) {
if (isEmpty()) head = tail = new Node(dataObj, null);
else head = new Node(dataObj, head);
}
public void insertAtBack(Object dataObj) {
if (isEmpty())
head = tail = new Node(dataObj, null);
else {
tail.setNext(new Node(dataObj, null));
tail = tail.getNext();
}
}
// Constructor
QueueByAggregation() {
qList = new LinkedList();
}
// Methods
public boolean isEmpty() { return qList.isEmpty(); }
public void enqueue(Object item) { qList.insertAtBack(item); }
public Object dequeue() {
if (qList.isEmpty()) return null;
else return qList.deleteFromFront();
}
public Object peek() {
return (qList.isEmpty() ? null : qList.head.getData());
}
}
}
}
& :
3 6
;
3
= " #
3 < , #
Employee#
% ( ;
; 1
#
1, .2? % .( StackByInheritance %
5(
LinkedList %/(# !
3 #
! # % .( $ #
QueueByAggregation %0( =
= LinkedList ; =
# # !
#
8 ;
= % (
' ;
!
+ #
Review Questions
, C # B
class Star {
String starName;
public String describe() { return "star " + starName; }
}
# Planet Star
starName
bodyName Star
starName
name Star
3 Planet HeavenlyBody
- C # B
class Planet {
String name;
Star orbiting;
public String describe() {
return "planet " + name + " orbiting " + orbiting.describe();
}
}
# Planet Star
starName
bodyName Star
starName
name Star
3 Planet HeavenlyBody
Chapter Summary
&&'
super
this() super() #
# #
instanceof
% ( % (
Programming Exercises
) Function evaluate !
int int G
; Half Function 4 !
evaluate() int /
+ # ! int
#
Half
H , :
! Function
Half
; Print Function#
int #
A # int 2 2>
:
@ # Half
Print