DES102 Object-Oriented Programming
DES102 Object-Oriented Programming
Grading schemes: In-class group exercises: 40% Midterm: 30% Final: 30%
Remarks:
1. In-class group exercises will take place during class.
2. The best ten scores out of at least 15 in-class group exercises (4 pts per
each for 10 in-class group exercises) will be used to calculate the final grade.
3. No make-up group exercises will be allowed for any reason, as each student
can be absent without affecting the grades by using this system.
4. Due to the large class size, attending lectures and participating in group
exercises in the non-registered section is strictly prohibited.
Teaching materials: Lecture slides and exercise files are available on Google
Classroom.
Teaching Style: Hands-on teaching using Power point slides and exercise sheets,
and group activities for effective learning.
DES102 Object-Oriented Programming
Instructor: Assoc. Prof. Dr. Pakinee Aimmanee
First-Half Material
1
DES102 Object Oriented Programming
2
Topic 1
Introduction to Java and OOP
Objectives:
• To learn about the history of Java language
• To learn about how Java code get executed before
get printed out at the console
• To write some basic Java programs
• To learn how to write a main method
• To learn about the dot operator (.)
• To learn about the + operator for concatenate String
and a number
• To learn about basic printout statements
3
OOP Vs Non-OOP
4
Why we need to learn OOP?
5
Learning OOP through JAVA
6
Java History
7
Java Runtime Environment(JRE)
8
JRE Components
• The class loader loads all classes necessary such as
library for the execution of a program
9
Java Virtual Machine (JVM)
10
Objects and Classes
11
How to model an object through simple
descriptions.
12
A dog
Properties:
- 2 eyes
- 2 ears
- 1 nose
- 4 legs
- 1 tail
- 1 long face
Actions:
- bark
- run
- eat
13
A Circle
• Properties
– Radius: An equal distance from any point along
each circle’s circumference to a unique point so-
called center
14
Active learning 1: Your object
15
Using Java to model an object
using a Java class’s keyword
16
Classes in Java
17
Class Components
• Properties
– Type declared variables associating to object’s properties
• Constructors
– Definition of ways to create the instances of object
• Methods
– Definition of functions associating to actions of the object
18
Class Properties
19
Constructor: a channel to create an object
• A constructor must
– have the same name as the class name
– provide details of required inputs (if any) for creating
the object.
– have no return type
20
Ready to write your first Java program?
21
Object: UnitCircle
• Property:
– Radius = 1
• Actions:
– Compute area
– Compute diameter
22
Our first program: UnitCircle
Written with a no-argument constructor
1
• Property:
width = 1
1
• Actions:
– Compute the area
– Compute the perimeter
24
Write together: UnitSquare
Written with a no-argument constructor
26
UnitCircle.java and • Because they are just the templates that
UnitSquare.java inform object’s definitions.
cannot run,
Do you know why? • We need a main method to run the
program.
27
How to write make it runnable?
28
The “main” method
• It must appear as
29
A class with a main method
public class TestUnitCircle
{ public static void main(String [ ] args)
{
}
} 30
Separation of an object class
and a runnable class
31
Let us create some objects
32
The new Operator
33
TestUnitCircle with a main method
public class TestUnitCircle class UnitCircle
{ int radius = 1;
{ public static void main(String [ ] args)
UnitCircle( )
{ UnitCircle c1 = new UnitCircle(); {
UnitCircle c2 = new UnitCircle(); }
} double findArea()
{ return 3.14*radius*radius;
}
}
The class TestUnitCircle.java is another file int findDiameter()
but must be in the same location as { return 2*radius;
UnitCircle.java, so it can use the information of
}
the class UnitCircle.
}
We say c1 and c2 are instances of UnitCircle.
34
Object’s profiles
radius
35
Let us get a property and/or
call methods of c1 and c2
36
The dot operator (.)
• The dot operator (.) is used for accessing the properties
or methods of the objects class UnitCircle
{ int radius = 1;
UnitCircle c1 = new UnitCircle(); UnitCircle( )
UnitCircle c2 = new UnitCircle(); { }
double findArea()
int rc1 = c1.radius; { return 3.14*radius*radius;
int rc2 = c2.radius; }
int findDiameter()
int area1 = c1.findArea(); { return 2*radius;
int area2 = c2.findArea(); }
}
39
Printing something to console
• System.out.println(arg) prints arg and also add new line after the
printout
– void System.out.println(boolean x)
– void System.out.println(char x)
– void System.out.println(int x)
– void System.out.println(long x)
– void System.out.println(float x)
– void System.out.println(double x)
– void System.out.println(char x[])
– void System.out.println(String x)
– void System.out.println(Object x)
40
String
41
The + operator
• Addition
int x = 2, y =3;
int z = x + y;
42
class UnitCircle
{ int radius =1;
Using the + operator UnitCircle( )
{
}
double findArea()
{ return 3.14*radius*radius;
}
public class TestUnitCircle int findDiameter()
{ return 2*radius;
{ public static void main(String [] args) }
{ UnitCircle c = new UnitCircle(); }
43
Fill in the missing statements
class UnitSquare
class TestUnitSquare { int width =1 ;
UnitSquare()
{ public static void main(String [] args)
{
{ // use the new keyword to create a UnitSquare s }
int findArea() {
return width*width;
}
int findPerimeter() {
//use . operator to call a method findArea() of s
return 4 *width;
}
}
}
} 44
* Assume that TestUnitSquare.java is in the same location with UnitSquare.java
Comments in Java
• Comments are code’s parts that is not read by the JVM.
• Two ways to write a comment
// This is a comment
or
/* This is a comment */
• //… is usually used for a short comment. The length of
the comment must be no more than 1 line.
• /* … */ is usually used for a long comment. The program
detects /* and */ as the beginning and the end of the
comment.
Ex. // This is a test
/* This part is a test. This part is a test. This part is a test.
This part is a test. This part is a test. This part is a test. */ 45
Active learning 3: Constructing an object
46
Topic 2:
Class Components in more detail
Objectives:
• to study details of properties, constructors and methods
in a class
• to study types of constructors
• Internal constructor chaining using the this keyword
• to study methods in a class
47
Class Components
• Properties
• Constructors
• Methods
48
Class’s Properties
• Class’s Properties are sometimes called attributes, fields,
or variables
• Types of class’s properties
primitive type: int, float, double, char, …
object type: type created from a class
Type Default value
int 0
double, float 0.00
char ‘\u0000’ (a null character)
boolean false
reference type (object type) null
49
How properties get assigned values
class Circle public class TestUnitCircle
{ int xcenter; { public static void main(String [] args)
int ycenter; { Circle c = new Circle(1, 3, 5.0);
double radius; double c_area = c.findArea();
S.O.P(“The area of c is ”+ c_area);
Circle(int x, int y, double r)
}
{ xcenter= x;
}
ycenter = y;
radius = r;
} Properties Circle c
double findArea() {
xcenter
return 3.14*radius*radius; }
ycenter
double findDiameter() {
radius
return 2*radius; }
} 50
An object class with an object property
51
An object can have another object as a property
class Person class Date{
{ String name; int day;
int age; int month;
int year;
double salary;
Date dob; //date of birth Date (int d, int m, int y)
boolean married; { day = d;
month=m;
char gender; //f=female, m=male year = y;
}
Person( ) }
52
* Assume that Person.java is in the same location with Date.java
class Person
54
Constructors
55
Types of Constructors
56
class Point with a no-arg constructor
}
}
}
Properties Point p
int x
int y
y = b;
}
}
62
Defining a Method
• The syntax for defining a method is as follows
returnType methodName(list of parameter)
64
An example of a class with overloading methods
class TestGreeting
class Greeting { public static void main(String [] args)
{ Greeting( ) { } { Greeting g = new Greeting();
g.Hello();
void Hello() { g.Hello(“Tim”);
Hello(1); g.Hello(2);
} }
void Hello(int t) { }
67
Using the this keyword to call another
constructor
68
class Point Constructor chainging
{ int x = 3 ; via the this call.
int y = 4;
class Point
Point (int x, int y)
{ int x = 3 ;
{ x = a;
int y = 4;
y = b;
Point (int a, int b)
}
{ x = a;
Point(int v )
y = b;
{ x = v;
}
y = v;
Point(int v) {
}
this (v, v);
Point( )
}
{ x = 0;
Point() {
y = 0;
this (0);
}
}
}
}
Without using the this call With the this call 69
Identify the outputs
class TestPoint class Point
{ public static void main(String [] args) { int x = 3 ;
{ Point p0 = new Point( ); int y = 4;
Point (int a, int b)
Point p1 = new Point(2, 7);
{ x = a;
Point p2 = new Point(5); y = b;
S.O.P(p0.x); }
S.O.P(p1.y); Point(int v) {
S.O.P(p2.x); this (v, v);
}
}
Point( ) {
} Properties Point p0 Point p1 Point p2 this (0);
int x }
int y }
70
Another use of the this keyword
71
class Circle {
int xcenter; An example of the use of
int ycenter; the keyword this
double radius;
double findArea()
{ return 3.14*radius*radius; }
double findDiameter()
{ return 2*radius; }
} 72
Using the this keyword for differentiating
the arguments and properties of the same names
class Point class Point
{ int x = 3 ; { int x = 3 ;
int y = 4; int y = 4;
Point (int a, int b) Point (int x, int y)
{ x = a; { this.x = x;
y = b; this.y = y;
} }
Point( ) Point( )
{ x = 0; { x = 0;
y = 0; y = 0;
} }
} }
73
Active learning 4: Trace the code on a class with
multiple constructors
74
Topic 3:
Static variables/methods and UML
Objectives:
• To learn the meaning of instance and static
variables and methods
• To learn about how to use static and instance
variables/methods
• Learn Unified Modeling Language for viewing
class skeleton
75
Types of Variables and Methods
• Instance variables/methods are variables/methods
that belongs to each individual instance (object).
• Static variables/methods are variables/methods that
belong to the class and not to a specific object.
– They are sometimes called class’s variables and
methods.
– These variables and methods can be accessed from
the class name directly.
– The keyword static is put in front of its type.
– They are used to model variables or methods that
are not depends on the object.
76
The use of static variables/methods
77
Static Vs Instance
methods or variables
class Child Properties Child jill Child jack
shared individual
{ int candy ;
int candy
static int money = 10;
void eatCandy()
Child( ){
int money
candy=5 ;
void payMoney( )
}
void eatCandy() {
candy=candy-1; class TestChild
} { public static void main(String [] args)
{ Child jill = new Child();
static void payMoney( )
Child jack = new Child();
{ money = money-1;
}
}
}
}
79
class Child
Identify the outputs { int candy ;
static int money = 10;
class TestChild Child( ){
{ public statics void main(String [] args) candy=5 ;
{ Child jill = new Child();
Child jack = new Child(); }
S.O.P(jack.candy); void eatCandy() {
S.O.P (jack.money); candy=candy-1;
S.O.P(jill.candy);
}
S.O.P(jill.money);
static void payMoney( )
{ money = money-1;
jill.eatCandy(); }
jill.payMoney( ); }
S.O.P(jack.candy);
S.O.P(jack.money);
S.O.P(jill.candy); Properties Child jill Child jack
S.O.P(jill.money);
int candy 5 5
Child.payMoney( ); void eatCandy()
S.O.P (jack.money);
S.O.P(jill.money); int money 10
S.O.P(Child.money); void payMoney( )
}
}
80
class Circle {
int xcenter;
int ycenter;
double radius;
static int CircleCount=0;
83
Example:
class Person
{ String name;
Invalid call to a non-static
static int numPerson=0; method from a class name
Person(String name) {
class TestPerson
this.name=name;
{ public static void main(String [] args)
numPerson++;
{ Person.introduce();
}
}
void introduce()
}
{ S.O.P(“Hello, nice meeting you”);
}
static void greeting() { S.O.P(“Hello”);
}
}
84
class Person An instance can call properties
{ String name; and methods which are
static int numPerson=0;
static or non-static
Person(String name) { class TestPerson
this.name=name; { public static void main(String [] args)
numPerson++; { Person p1 = new Person(“John”);
} Person p2 = new Person(“Ted”);
void introduce() S.O.P(p1.name);
{ S.O.P(“Hello, nice meeting you”); S.O.P(p2.numPerson);
} p1.introduce();
static void greeting() { S.O.P(“Hello”); p2.greeting();
} }
} }
Person p1 Person p2
String name
void introduce ()
int numPerson
void greeting()
85
class Person
{ String name;
static int numPerson=0; Example:
Person(String name) { Valid calls from the main method
this.name=name;
numPerson++;
} Person p1 Person p2
void introduce() String name
{ S.O.P(“Hi, I am ” + name);
} void introduce ()
static void greeting() { S.O.P(“Hello”); int numPerson
public static void main(String [] args)
{ Person p1 = new Person(“Jane”; void greeting()
Person p2 = new Person(“Jim”) void main(String [] arg)
S.O.P(numPerson);
greeting();
S.O.P(Person.numPerson);
Person.greeting(); The main method is static, it
S.O.P(p.name); can access methods and
p.introduce(); properties that are static.
S.O.P(p.numPerson);
p.greeting(); Static methods/properties
} can be accessed through
} class name.
86
The static math methods
in the Math Class
• The Math class is in the Java.lang.Object package.
• The Math Methods in Math classes are all static
methods, thus they can be accessed through the class
name directly.
Ex.
class Math{
static double sqrt(double x) {..}
static double sin(double x) {..}
static double ceil(double x) {..}
static double pow (double x, double y) {..}
static double max(double a, double b) {..}
…
}
87
Ex. Calling static methods of the Math class
class TestMath
{ public static void main(String [ ] args)
{ S.O.P(Math.pow(2.0, 4.0););
S.O.P(Math.sqrt(4.0));
S.O.P(Math.max(4.5, 7.9);
}
}
88
Unified Modeling Language(UML)
89
Unified Modeling Language (UML)
90
class Circle { UML of Circle
int xcenter=0;
int ycenter=0;
double radius=1.0;
static int circleCount=0; Circle
Circle(double radius) { xcenter: int
this.radius=radius; ycenter: int
circleCount++; } radius: double
circleCount:int
Circle(int xcenter, int ycenter,
double radius) Circle(radius:double)
{ this.xcenter = xcenter; Circle(xcenter:int, ycenter:int,
this.ycenter = ycenter; radius:double)
findArea():double
this.radius =radius; findDiameter(): double
circleCount++;
}
double findArea()
{ return radius*radius*3.14;
}
double findDiameter()
{ return 2*radius; }
} 91
Draw a UML for the class Person
class Person
{ String name;
static int numPerson=0;
Person(String name) {
this.name=name;
numPerson++;
}
void introduce()
{ S.O.P(“Hi, I am ” + name);
}
static void greeting() { S.O.P(“Hello”);
}
}
92
Active learning 5: Tracing the code with static
variables and methods
93
Topic 4: Visibility Modifiers,
Encapsulation
Objective:
• To learn about how data can be protected so that only
programs in certain scopes/locations can access it.
94
A package in Java
95
Encapsulation
96
Visibility Modifiers
97
Summary of visibilities
98
The Import keyword
99
package p1;
public class Circle {
int xcenter=0;
int ycenter=0;
private double radius=1.0; p1
public static int circleCount=0;
xcenter
ycenter
public Circle(double r) { -radius
radius=r; +circleCount
circleCount++;
+Circle(r)
} +Circle(x, y,r)
public Circle(int x, int y, double r) findArea()
{ xcenter=x; findDiameter()
ycenter=y; Circle.java
radius=r;
circleCount++;
}
double findArea() { return 3.14*radius*radius;}
double findDiameter(){return 2*radius;}
100
}
package p1;
Accessibility within a
public class TestCircle{ package
public static void main(String [] args)
{ Circle c = new Circle(1.0);
p1
}
}
xcenter
ycenter c.xcenter
-radius c.ycenter
+circleCount c.radius
c.circleCount
What happen if we put each of these +Circle(r)
statements to the box? +Circle(x, y,r) c.findArea()
System.out.println(c.circleCount); findArea() c.findDiameter()
System.out.println(c.xcenter); findDiameter()
System.out.println(c.ycenter);
Circle.java TestCircle.java
System.out.println(c.radius);
c.xcenter= 5;
c.ycenter= 1;
c.radius = 4;
101
package p2;
import p1.Circle;
Accessibility outside a
package
public class TestCircle2{
public static void main(String [] args)
{ Circle c = new Circle(); p2
} c = new Circle(1.0)
} c.xcenter
c.ycenter
c.radius
What will happen if we put each of these c.circleCount
statements to the box? c.findArea()
System.out.println(c.circleCount); c.findDiameter()
System.out.println(c.xcenter);
System.out.println(c.ycenter); TestCircle2.java
System.out.println(c.radius);
c.xcenter= 5;
c.ycenter= 1;
c.radius = 4;
c.circleCount++;
How to access private properties/methods?
103
package p1;
public class Circle {
int xcenter=0;
int ycenter=0; p1
private double radius=1.0;
public static int circleCount=0; xcenter
ycenter
-radius
public Circle(double r) { this( 0, 0, r); } +circleCount
public Circle(int x, int y, double r)
+Circle(r)
{ xcenter=x; +Circle(x, y, r)
ycenter=y; +getRadius()
radius=r; +setRadius(r)
findArea()
circleCount++; findDiameter()
}
Circle.java
public double getRadius() {return radius; }
void setRadius(double r) {radius = r; }
double findArea() { return 3.14*radius*radius;}
double findDiameter(){return 2*radius;}
}
104
package p1;
Accessibility within the
public class TestCircle{ same package
public static void main(String [] args)
{ Circle c = new Circle(1.0);
S.O.P(c.getRadius());
c.setRadius(3.0); p1
}
xcenter c.xcenter
} ycenter c.ycenter
-radius c.radius
+circleCount c.circleCount
+Circle(r) c.findArea()
+Circle(x, y,r) c.findDiameter()
findArea() c.getRadius()
findDiameter() c.setRadous(3.0)
+getRadius()
setRadius(r)
Circle.java TestCircle.java
105
package p2;
import p1.Circle;
Accessibility outside a
package
public class TestCircle2{
public static void main(String [] args)
{ Circle c = new Circle(); p2
S.O.P(c.getRadius());
} c = new Circle(1.0)
} c.xcenter
c.ycenter
c.radius
c.circleCount
c.findArea()
c.findDiameter()
c.getRadius()
TestCircle2.java
Topic 5: Inheritance
and constructor chaining
Objectives:
107
Inheritance
108
Circle Vs Cylinder
109
Super Class and Subclass
110
Inheritance
• A subclass inherits all non-private superclass’s properties and
methods from the superclass
• A subclass usually represents a subtype of the superclass. It
usually has more specific properties and/or methods than that
of the superclass.
For instance,
111
Active learning 6: Thinking of other pairs of super
class-sub class
112
“extends” and “super”
114
Inheritance rules…cont.
• The caller can access the properties and the methods of
the super class via subclass’s instance.
115
class Circle {
Defining a cylinder as a int xcenter= 1;
subclass of Circle int ycenter = 1;
double radius =1.0;
class Cylinder extends Circle Circle( ) { this(0, 0, 1.0); }
Circle(int x, int y, double r)
{ double height; { xcenter = x;
Cylinder() { super( ); ycenter = y;
height=1.0; } radius = r;
}
Cylinder(int x, int y, double r, double height) Circle(double r) { this(0, 0, r); }
{ super(x, y, r); double findArea()
this.height=height; { return 3.14*radius*radius;
}
} double findDiameter()
double findVolume() { return 2*radius;
{ return super.findArea()*height; }
}
}
}
Circle is an inherited class,
where as Cylinder is an
inheriting class.
116
Identifying the output
public class TestCylinder
{ public static void main(String [ ] args)
{ Cylinder cyl1 = new Cylinder(0, 0, 1.0, 2.0);
Cylinder cyl2 = new Cylinder( );
}
}
double height
int xcenter
int ycenter
double radius
117
A subclass cannot access the private
properties or methods of the super class
class Cylinder extends Circle class Circle {
int xcenter;
{ double height; int ycenter;
Cylinder() { super( ); private double radius;
height=1.0; } Circle( ) { this(0, 0, 1.0); }
Circle(int x, int y, double r)
double findVolume() { xcenter = x;
{ return super.findArea()*height; ycenter = y;
} radius = r;
}
void printRadius() { Circle(double r)
S.O.P(super.radius); } { this(0, 0, r);
} }
private double findArea()
} Trying to access private { return 3.14*radius*radius;
properties and methods in }
the super class causes
double findDiameter()
compilation errors.
{ return 2*radius;
} 118
}
When Circle has a private property
class Cylinder extends Circle class Circle {
{ double height; int xcenter;
int ycenter;
Cylinder() { super( );
private double radius;
height=1.0; } Circle( ) { this(0,0,1.0); }
Cylinder(int x, int y, double r, double h) Circle(int x, int y, double r)
{ super(x, y, r); { xcenter = x;
height=h; ycenter = y;
radius = r;
}
}
double findVolume() Circle(double r)
{ return super.findArea()*height; { this(0, 0, r); }
} double findArea()
} { return 3.14*radius*radius; }
double findDiameter()
{ return 2*radius; }
}
119
Trace the program and identify the output
when each of following statement is uncommented
public class TestCylinder
{ public static void main(String [] args)
{ Cylinder cyl = new Cylinder(0, 0, 1.0, 2.0);
//S.O.P(cyl.radius);
//S.O.P(cyl.xcenter);
//S.O.P(cyl.ycenter);
//S.O.P(cyl.height);
//S.O.P(cyl.findVolume());
//S.O.P(cyl.findArea());
}
} Properties Cylinder cyl
double height
int xcenter
int ycenter
double radius 120
Overriding Method
121
Cylinder overrides findArea() of Circle
class Cylinder extends Circle class Circle {
{ double height; int xcenter;
Cylinder() { super(); int ycenter;
height=1.0; } double radius;
Circle( ) { this(1.0); }
Cylinder(int x, int y, double r, double h)
Circle(int x, int y, double r)
{ super(x, y, r); { xcenter = x;
height=h; ycenter = y;
} radius = r;
double findArea() { }
Circle(double r) {
return 2*super.findArea()
this(0, 0, r);
+ 6.28**radius*height; }
} double findArea() {
double findVolume() { return 3.14*radius*radius; }
return super.findArea()*height; } double findDiameter()
{ return 2*radius; }
}
}
122
Identify the outputs
public class TestCylinder
{ public static void main(String [] args)
{ Cylinder cyl = new Cylinder(0, 0, 1.0, 2.0);
S.O.P(cyl.findArea());
S.O.P(cyl.findDiameter());
}
}
124
Default super
125
class Circle {
A default super() int xcenter;
int ycenter;
class Cylinder extends Circle
double radius;
{ double height; Circle( ) { this(1.0); }
Cylinder(double height) Circle(int x, int y, double r)
{ { xcenter = x;
ycenter = y;
radius = r;
this.height=height;
}
} Circle(double r) {
} this(0, 0, r);
-------------------------------------------------- }
}
public class TestCylinder
{ public static void main(String [ ] args) Properties Cylinder cyl
{ Cylinder cyl = new Cylinder(2.0); double height
int xcenter
} int ycenter
} double radius
126
** a default super will be added in class by an instructor.
Accessing properties or methods of the superclass
without the super.
127
Accessing properties or class Circle {
int xcenter;
methods of the superclass int ycenter;
without the super. infront double radius;
Circle( ) {
class Cylinder extends Circle this(1.0);
{ double height =2.0; }
Cylinder(double height) Circle(int x, int y, double r)
{ super(); { xcenter = x;
this.height=height; ycenter = y;
radius = r;
}
}
double findSideArea() Circle(double r) { this(0, 0, r);
{ return 3.14*findDiameter()*height; } }
} double findDiameter()
--------------------------------------------------- { return 2*radius; }
public class TestCylinder }
{ public static void main(String [ ] args) Properties Cylinder cyl
{ Cylinder cyl = new Cylinder(1.0); double height
S.O.P(c. findSideArea()); int xcenter
} int ycenter
} double radius 128
What happen when findArea() is
class Cylinder extends Circle
called rather than super.findArea()
{ double height;
Cylinder(int x, int y, double r, double h) class Circle {
{ super(x, y, r); int xcenter;
height=h; int ycenter;
} double radius;
Circle( ) { this(1.0); }
double findArea() {
Circle(int x, int y, double r)
return 2*findArea() + 6.28**radius*height; { xcenter = x;
} ycenter = y;
} radius = r;
------------------------------------------------------- }
Circle(double r) {
public class TestCylinder
this(0, 0, r);
{ public static void main(String [ ] args) }
{ Cylinder cyl = new Cylinder(0, 0, 1.0, 2.0); double findArea() {
S.O.P(cyl. findArea()); return 3.14*radius*radius;
} }
}
}
129
What if we do not want our class to be inherited.
Can we prevent it from being extended?
130
The “final” keyword
131
Use final to prevent a class from being derived
by other class
132
Use final to prevent a variable from being
modified
class Point
{ final int x0 =0; Trying to change a value
final int y0 =0; from a final property causes
Point(){ } compilation error !
}
-----------------------------
class TestPoint
{ public static void main(String [] args)
{ Point p1= new Point();
p1.x0= 2;
}
} 133
Use final to
class Cylinder extends Circle
prevent a method { double height;
135
package p1; package p2;
public class Circle { import p1.Circle;
int xcenter= 0; class Cylinder extends Circle
public int ycenter = 0; { double height;
private double radius=1.0; Cylinder() { super();
static int circleCount=0; height=1.0; }
public Circle() {circleCount++;} Cylinder(double x, double y,
public Circle(double x, double y, double r) double r, double height)
{ xcenter=x; { super(x, y, r);
ycenter=y; this.height=height;
radius=r; }
circleCount++; Cylinder(int height){ this.height = height; }
} double findVolume()
double getRadius() { return radius; } { return super.findArea()*height;
protected double findArea() { }
return 3.14*radius*radius; }
}
A subclass Cylinder
double findDiameter(){return 2*radius;} located outside p1
} can still access findArea
of Circle because it is
marked as protected
136
package p1; package p1;
public class Circle { public class TestCircle1{
int xcenter=0; public static void main(String [] args)
int ycenter=0; { Circle c = new Circle(2.0);
private double radius=1.0; S.O.P(c.getRadius()) ;
public static int circleCount=0; c.setRadius(4.0);
public Circle(double r) { }
radius=r;
}
circleCount++;
--------------------------------------
}
package p2;
public Circle(int x, int y, double r)
import p1.Circle;
{ xcenter=x; public class TestCircle2{
ycenter=y; public static void main(String [] args)
radius=r; { Circle c = new Circle(2.0);
circleCount++; S.O.P(c.getRadius()) ;
} }
public double getRadius(){ return radius;}
double setRadius(double radius) {
this.radius = radius; } S.O.P= System.out.println
double findArea() {
return 3.14*radius*radius;}
double findDiameter(){return 2*radius;}
137
}
Links between super class and subclass in UML
Circle
…
… A hollow head arrow
pointing from subclass
to the super class is
used in the UML
Cylinder
…
…
138
Constructor chaining in
multi-level inherited family
139
Constructor Chaining
140
Point
class Point
{ int x;
int y;
Point(){
x=y=0;
S.O.P(“no-arg constructor of Point”);
}
Point(int x, int y){
this.x = x;
this.y = y;
S.O.P(“2-arg constructor of Point”);
}
}
141
class Circle extends Point
{ double radius; Circle
Circle( ) { radius= 1.0;
S.O.P(“no-arg constructor of Circle”);
} Point
Circle(double radius) {
super();
this.radius=radius;
S.O.P(“1-arg constructor of Circle”); Circle
}
Circle(int x, int y, double r)
{ super(x, y);
radius=r;
S.O.P(“3-arg constructor of Circle”);
} 142
class Cylinder extends Circle
{ double height;
Cylinder
Cylinder() {
height=1.0;
S.O.P(“no-arg constructor of Cylinder”); Point
}
Cylinder(double height){ super();
this.height=height;
S.O.P(“1-arg constructor of Cylinder”); Circle
}
Cylinder(double radius, double height) {
super(radius);
this.height=height; Cylinder
S.O.P(“2-arg Constructor of Cylinder”);
}
Cylinder(int x, int y, double radius, double height) {
super(x, y, radius);
this.height=height;
S.O.P(“4-arg constructor of Cylinder”);
} 143
class FoodCan extends Cylinder Point
{ String food = “fish”;
145
class TestConstructor
{ public static void main(String [] args)
{
• Cylinder cyl3= new Cylinder(7.0);
}
}
146
class TestConstructor
{ public static void main(String [] args)
Identify the outputs {
}
}
147
Active learning 7: Trace a code on inheriting
classes
148
Topic 6:
Polymorphism
Objectives:
• To learn about the concept of Polymorphism
• To learn about to access properties and methods of a
variable which is declared as a superclass type but refer to
a subclass object.
149
Polymorphism and a polymorphic variable
151
Implicit Casting
152
Down casting
• A polymorphic variable can be casted back to it created
type by adding (subclasstype) in front of the variable
name.
153
Explicit Casting
• The explicit casting is applied to the implicit casted variable.
Circle C = new Cylinder(0, 0, 1.0, 2.0); (Cylinder) C;
Fruit f2 = new Apple(); (Apple) f2;
Apple f3 = new Fuji(); (Fuji) f3;
Fruit f4 = new Fuji(); (Fuji) f4;
154
instanceof Operator
155
Fruit f1 = new Fruit();
Fruit f2 = new Apple(); Using instanceof
Apple f3 = new Fuji();
Fruit f4 = new Fuji();
Circle c = new Cylinder(0, 0, 1.0, 2.0);
The following statements print true
System.out.print(f1 instanceof Fruit);
System.out.print (f2 instanceof Apple);
System.out.print (f3 instanceof Apple);
System.out.print (f4 instanceof Fuji);
System.out.print (c instanceof Cylinder);
156
Early binding VS Dynamic Binding
157
Dynamic Binding
• Is when type of the object is determined at run-time
Ex Circle cc= new Cylinder(0, 0, 1.0, 2.0);
S.O.P( cc.findArea() ) ; Whose findArea() will be used?
158
Whose method to be used for
a polymorphic variable
Yes No
159
Whose property to be used for a
polymorphic variable
Yes No
160
class Cylinder extends Circle class Circle {
{ double height; int xcenter;
Cylinder(int x, int y, double r, int ycenter;
double height) double radius;
Circle(int x, int y, double r)
{ super(x, y, r); { xcenter = x;
this.height=height; ycenter = y;
} radius = r;
double findArea() { }
return 2*super.findArea() + double findArea()
{ return 3.14*radius*radius;
6.28*radius*height; }
} }
}
1 class TestDynamicBinding {
2 public static void main(String [] args){
3 Circle cc= new Cylinder(0, 0, 1.0, 1.0);
4 System.out.println(cc.findArea());
5
6 }
7}
161
How to make a polymorphic variable be able to
access properties/methods defined in the
created class
The answer is caste it to the created type before calling the
property or method.
162
The use of polymorphic variable
• Passing a subclass instance to a method that requires a
superclass type. class TestDrinkMaker
{ public static void main(String [] args)
class DrinkMaker { Fruit ft = new Fruit();
{ DrinkMaker() { }
Apple ap = new Apple();
Fuji fj = new Fuji();
void makeAppleJuice(Apple apple)
DrinkMaker dm = new DrinkMaker();
{ S.O.P(“Buzzzzzzzz”);
S.O.P(“Here is your apple juice”);
} dm.makeFruitJuice(ft);
void makeFruitJuice(Fruit fruit) dm.makeFruitJuice(ap);
{ S.O.P(“Buzzzzzzz”); dm.makeFruitJuice(fj);
S.O.P(“Here is your fruit juice”); dm.makeAppleJuice(fj);
} }
} }
163
Active learning 8: Trace a code on problems with
polymorphic variables
164
Topic 7:
Abstract Classes
and Interfaces
Objectives:
• To learn about classes that are abstract
• To learn about methods that are abstract
• To learn about Interface
• To learn about the UML of the abstract classes
and interface
165
Abstract objects
166
Ex Sadness
167
Abstract Classes
168
Abstract class’s s components
169
Example: Two dimensional shape
170
Defining an abstract class: Shape
171
A subclass of an abstract class
abstract class TwoDShape {
int numSides;
class Rectangle extends TwoDShape Shape(int numSides) {
{ double width; this.numSides=numSides;
}
double length; void printAbstractType() {
S.O.P(“Shape”); }
Rectangle(double width, double length)
{ super(4); abstract double findArea();
abstract double findPerimeter();
this.width= width;
this.length= length; }
}
/*These methods must define content of abstract methods
double findArea() { return width*length; }
double findPerimeter() { return 2*(width+length); }
}
172
Determining the outputs
class TestRectangle
{ public static void main (String [ ] args)
{ Rectangle r = new Rectangle(3.0, 4.0);
S.O.P(r.findArea());
}
}
173
Abstract Classes Illustration
• In the UML, the abstract
TwoDShape
class name and abstract
numSides: int methods’ names are
italicized
Shape(numSides: int)
• The link between an
printAbstractType() : void
abstract parent and the
findArea():double
subclass is solid line
findPerimeter(): double
• The arrow head is hollow
Triangle Rectangle
… …
… …
findArea():double findArea():double
findPerimeter(): double findPerimeter(): double
174
Rules on Abstract classes
• Abstract classes are like regular classes with data and methods,
but it cannot be created using the new operator.
• The abstract class can be as a parent class and as a type.
Ex Shape obj;
• A class containing an abstract method must be an abstract class.
• However, an abstract class need not necessarily contain the
abstract methods.
Trying to create an
instance from an
abstract class will cause
a compilation error
175
Interfaces
176
Interface Vs Abstract class
• They both can be used to model an abstract object.
177
Interfaces
178
Interface …continue
179
Abstract object Edible
180
Defining an interface Edible
181
UML of an interface and its subclass
Edible
• The UML of the interface class
is marked written with
+ tellHowToEat(): String <<interface>> on the top box
+ printType(): String
• A subclass of an interface is
represented by a dash line with
a hollow triangle head
182
When a class derives from an interface
183
Defining a class with abstract or interface parents
<interface> <interface>
Animal
Vehicle Flyer
Airplane Bird
interface ActionListener {
public void actionPerformed(ActionEvent e);
}
----------------------------------------------
187
188
DES102 Exercises
Book 1
1
Exercises
Introduction to OOP
2
Do-It-Together Exercises
Introduction to OOP
Exercise 1: Consider the following java program. Mark in the program properties,
constructors, and methods
class Bicycle {
int cadence = 1;
int gear = 2;
int speed = 0;
Bicycle()
{
}
3
Exercise 2 Define a class Rectangle with the following details.
Length=2
Properties: width and length, both are of type int. The width is preset to 1
Constructors: one constructor that takes no argument and has no content in its scope.
Methods:
int findArea( ): computes and returns the area of the rectangle
int findPerimeter( ): computes and returns the perimeter of the rectangle
double findDiagonal(): computes and returns the diagonal distance of the rectangle.
Remark. Use Math.sqrt(arg) to compute the square root of arg.
4
Exercise 3 Complete a java runnable class TestRectangle that tests the Rectangle class. In the
main method, do following.
1. Use the keyword new to create an object of Rectangle, name this object rec.
2. Assign the width of rec to 3 and the length of rec to 4.
3. Use the dot operator (.), printout statement, and the + operator to print out the information
and values of rec in the following format.
The object rec has a dimension of width X length.
Remarks. 1. the width and length in the printout is width of rec and the length of rec
Assume the class Rectangle defined in the previous problem is in the same location as
TestRectangle.
5
Self-Review Exercises
Intro to OOP
Exercise 1: Consider the Account program, mark parts in the program that are properties,
constructors, and methods.
class Account {
String name = “Somchai Jaidee”;
double balance = 0.0;
Account()
{
}
void quickWithdraw()
{
balance = balance – 1000;
}
Account clone()
{ Account temp = new Account();
return temp;
}
}
6
Exercise 2: Write a java class Person that has String firstName, String lastName, int
yearOfBirth as its properties. The firstName, lastName, yearOfBirth properties are
initialized with “Nick”, “Cage”, and 2000, respectively. It has only one constructor that
takes no argument and has no content. The class Person has one method int
computeAgeAtYear (int year). This method computes and returns the age of the person at
the input year.
7
Exercise 3 Write a java class TestPerson that can run and test the Person class. In the
main method, do following.
1. Use the keyword new to create an object of Person, name this object p.
2. Assign the firstName and lastName of the p to your name and last name.
3. Use the dot operator, printout statement, and the + operator to print out the
description of the information of p in the following format:
firstName lastName was born in yearOfBirth.
In year XXXX, this person will be XX years old.
where the XXXX is the input year and XX is calculated by calling to a method
computeAgeAtYear of the instance p. Remark. Assume the class Person is in the same
package as TestPerson.
8
Exercise 4: identify the output when the class TestPerson is run.
9
Exercise 5: Write a class Staff that has String id, String name, String position, and double salary as
properties. The properties id, name, position, and salary are initialized to “001”, “Manee”,
“secretary”, 20000.00, respectively. A class staff has one constructor that takes no argument and has
no content. There are 2 methods in this class. The first method void printName() which returns staff’s
name. Another method is printInfo() which calls the printName() method to print name and uses the
a printout statement to print position in the following format, name is a position.
class Staff {
…………………………………………………………………
…………………………………………………………………
…………………]
………………………………………………
Staff(){
void printName() {
void printInfo() {
10
Exercise 6 Create a java class BankAccount. It has three properties which are initialized
as follows: String ownerName = “Nathan G. Karpinski”, String accountNumber = “000-000-
0000”, and double balance = 0.00. It has one constructor that doesn’t take any arguments.
The content of the constructor is empty. There are 3 methods in this class: void
deposit(double amount) which deposits the input amount to the balance, void
withdraw(double amount) which withdraws amount from the balance, and void printInfo()
which print outs the information about ownerName, accountNumber, and balance of
BankAccount in the following format.
11
Exercise 7 Use the class BankAccount defined in the previous problem to do the
followings. Assume that the class BankAccount in the same package as
TestBankAccount.
Write a java class TestBankAccount with a main method that can run and test the
BankAccount class. In the main method of the TestBankAccount, do followings.
• Use the keyword new to create an object of BankAccount, name this object bacc.
• Change the information of the first name, last name, account number, and balance
with
12
Exercise 8: Identify the output when the class TestBankAccount is run.
13
Exercises
Class components in more detail
14
Do-It-Together Exercises
boolean isCentered() {
Exercise 1: The Message Panel Progrm. return centered;
}
Circle and label parts in this program that are properties,
constructors, and methods. void setCentered(boolean centered) {
this.centered = centered;
import javax.swing.*; repaint();
import java.awt.*; }
15
Exercise 2: Consider the class Dog below. Circle and label parts that are properties, constructors,
and methods.
class Dog
Dog()
{ System.out.println(“In a no-arg constructor”);
}
Dog(String name)
{
this.name = name;
System.out.println(“In a 1-arg constructor”);
void bark()
{ System.out.println(“Bok Bok”);
}
void sit()
{ System.out.println(name+ “ sits.”);
}
void hi5()
{ System.out.println(name+ “ hi5.”);
}
void perform()
{ sit();
hi5();
}
16
Exercise3: Consider another program. This program uses the information of the class
Dog in the previous exercise. Identify the output at the end of this program.
1 class DogFarm
2 {
3 static void changeName(Dog d, String newname)
4 { d.name = newname;
5 }
6 public static void main(String [] args)
7 {
8 Dog dog1 = new Dog(“Doodle”, “James”);
9 Dog dog2 = new Dog(“Jack”);
10 Dog dog3 = new Dog();
11
12 dog1.bark();
13
14 dog3.name= “Cola”;
15 System.out.println(“The new name of dog3 is ”+ dog3.name);
16
17 changeName(dog1, “Google”);
18 System.out.println(“The new name of dog1 is ”+ dog1.name);
19
20 dog2.owner= “Alice”;
21 System.out.println(“The owner of dog2 is ”+ dog2.owner);
22
23 dog3.sit();
24 dog2.hi5();
25 dog1.perform(2);
26 dog3.perform();
27 }
28 }
17
Identify the output from the specify lines
10
12
14-15
17-18
20-21
18
23
24
25
26
19
Exercise 4 Trace the code TestRectInSpac and identify the outputs using the classes
Point and RectInSpace defined as follows.
class Point
{ int x;
int y;
Point(int x, int y)
{ this.x = x;
this.y = y;
System.out.println(“A point is constructed”);
}
}
class RectInSpace
{ Point upperLeft;
int width;
int height;
RectInSpace( )
{ this(new Point(0, 0), 1, 1);
S.O.P(“A RectInSpace is constructed from a no-arg constructor”);
}
RectInSpace(Point p, int width, int height )
{ upperLeft = p;
this.width = width;
this.height = height;
S.O.P(“A RectInSpace is constructed from a 3-arg constructor”);
}
void shiftLeft() { upperLeft.x = upperLeft.x - 1 ; }
void shiftRight() { upperLeft.x = upperLeft.x + 1 ; }
void shiftUp() { upperLeft.y = upperLeft.y - 1 ; }
void shiftDown() { upperLeft.y = upperLeft.y + 1 ; }
}
20
S.O.P(rs1.upperLeft.x);
S.O.P(rs2.upperLeft.y);
rs1.shiftRight();
rs2.shiftUp();
S.O.P(rs1.upperLeft.x);
S.O.P(rs1.upperLeft.y);
S.O.P(rs2.upperLeft.x);
S.O.P(rs2.upperLeft.y);
}
}
21
Self-Review Exercises
Exercise 1 Circle and label parts that are properties, constructors, and methods of the
given java program. S.O.P= System.out.println
class Person {
String name;
String occupation;
Person(){
this(“Eve Sandel”, “nurse”);
}
Person(String name){
this(name, “teacher”);
}
void introduce(){
S.O.P(“My name is ”+ name + “. I am a ” + occupation);
S.O.P(“Nice to meet you”);
Exercise 2 Consider following java program. This program uses the information of the class
Person in the previous page. Identify outputs at a line of this code.
1 class PersonDemo {
2 public static void main(String[] args) {
3
4 Person a = new Person();
5 a.introduce(“Hello”);
6
7 Person b = new Person("Emily Brown”,"doctor");
8 b.introduce();
9
10
11 }
12 }
22
Line no. Outputs
4
23
Exercise 3 class Date. The class Date has three properties: int day, int month, int year. It
has one constructor that takes 3 arguments: int day, int month, int year. The constructor
assigns the input arguments to its corresponding properties. The class Date has only one
method which is void printDate( ) which prints the date in the format of day-month-year.
Exercise 4: Write a java class Name. The class Name has two properties: String
firstName and String lastName. It has one constructor that takes 2 arguments: String
firstName, String lastName. The constructor assigns the input arguments to its
corresponding properties. The class Name has only one method which is void printName(
) which prints the firstName lastName with a space between them, for example, Jeff March
24
Exercise 5: Write a class StudentID.
The StudentID class has four properties: Name name, String studentID, Date
dateOfBirth, and String department.
It has 4 methods.
void print(String text) which prints out the input text without adding a new line after it
in the format of text:.
void printStudentID( ) which prints out StudentID with a new line after the printout,
void printDepartment() which prints out the department with a new line after the
printout
void makeCard() which printout card in the below format. The program should call
print(Sring text) method of this class, printName( ) of name, printDate( ) of dateOfBirth,
printStudentID() and printDepartment() of this class
SIIT ID CARD
ID: studentID
DOB: day-month-year
Department: department
25
Exercise 6: Write a runnable class Test StudentID. In the main method of this class, do
following.
26
Exercise 8 consider following java program and answer the questions at the end of the
program. Circle and labels parts in this program that are properties, constructors and
methods.
class Pet
{ String name = “Cola”;
String type = “Dog”;
int age = 1;
double weight = 2;
Pet(String name )
{ this.name=name;
S.O.P("in a 1-arg constructor");
}
27
Exercise 9: Use the program pet in the previous exercise. What should be the outputs if
the following statements are executed in the main method? S.O.P= System.out.println
10
28
Exercises
29
Do-It-Together Exercises
Static properties/method, UML
Rectangle() {
this(1.0,1.0);
System.out.println("A no-arg constructor is called");
}
Rectangle(int side) {
this(side,side);
System.out.println("A 1-arg constructor is called");
}
double calculateCost(){
30
}
b) Writing a UML diagram for the class Rectangle defined in part a).
31
Exercise 2 Identify the outputs
10
32
Self-Review Exercises
Exercise 1 Mark and label static properties and static methods in this class.
class Pyramid
{ int length;
int width;
int height;
static int noOfPyramid=0;
Pyramid(int val)
{ this(val, val, val);
System.out.println("Created from a 1-arg constructor ");
}
int findVolume()
{ return (length*width*height)/3;
}
int findBaseArea(){
return length*width;
}
String getInfo(){
return length+"-"+width+"-"+height;
}
33
b) Write the UML of class Pyramid
34
Exercise 2 Identify outputs when the following statements are executed in the main methods of
the pyramid program.
1 class TestPyramid
2 { public static void main(String [] args){
3 Pyramid a = new Pyramid(10, 10, 25);
4 System.out.println(a.getInfo());
5 System.out.println(a.findBaseArea());
6 Pyramid b = new Pyramid(3);
7 System.out.println(b.getInfo());
8 Pyramid c = new Pyramid(10,15,20);
9 new Pyramid(9);
10 System.out.println(a.findNoOfPyramid());
11 System.out.println(b.findNoOfPyramid());
12 System.out.println(Pyramid.findNoOfPyramid());
13
14 }
15 }
Line number Output
10
11
12
35
1
Exercise 3 Which statements cause a program a compilation error when put at line 13 of
TestPyramid.
System.out.println(c.width);
System.out.println(c.legnth);
System.out.println(c.height);
System.out.println(c.noOfPyramid);
System.out.println(c.findBaseArea());
System.out.println(c.findVolume());
System.out.println(c.findNoOfPyramid());
System.out.println(c.getInfo());
36
Exercise 4: a) Circle and label instance variables/methods, static variables/methods and
write UML for this class.
Ball(){
numBall++;
totalPrice+=unitPrice;
System.out.println("A new ball is generated");
}
int findDiameter(){
return 2*radius;
}
double findVolume(){
return (4.0/3)*3.14*Math.pow(radius, 3);
}
void printBallInfo(){
System.out.println("Ball radius : "+radius+
" Color: "+ color+" Price : " + unitPrice);
}
37
b) Write the UML of class Ball
38
Exercise 5 Identify outputs when the following program is executed.
1 class TestBall
39
Exercises
Visibility Modifiers
40
Do-It-Together Exercises
Visibility modifiers
41
Self-Review Exercises
Visibility modifiers
Exercise 1 Put appropriate keywords and visibility modifiers (static, private, and public) in
the program below so that it fulfils the following requirements.
1. numAccount keeps the number of BankAccount objects created both inside and
outside package.
2. The numAccount must be accessible anywhere.
3. ownwerName, accountNumber, and balance variables can only be accessed inside of
the BankAccount class, but not anywhere else.
4. deposit and withdraw methods must be accessible anywhere
5. printInfo method can only be accessed inside of the BankAccount class and within
the package Developer
package Developer;
void printInfo()
{ S.O.P(ownwerName+"\t"+accountNumber+"\t"+balance );
}
42
Exercise 2: Consider the following program
package p1;
package p1;
public class TestRightTri
public class RightTri
{ public static void main(String [] a)
{ protected static int count=0;
{ RightTri rt1= new RightTri(3, 4);
private int base;
int height;
Box1
public RightTri(int base, int height )
}
{ this.base= base;
}
this.height=height;
count++;
}
package p2;
public RightTri()
import p1.RightTri;
{ this(3, 4);
}
public class RightTriPrism extends
RightTri
static double findDiagonal()
{ int length;
{ return Math.sqrt(base*base+
height*height;
public static void main(String [] a)
}
{ RightTri rt2= new RightTri(12, 5);
String getBase(){ return base;}
public String getHeight(){
return height; Box2
}
public double findArea()
}
{ return 0.5*base*height;
}
}
}
43
Exercise 3: Consider the following program.
package p1;
Ball(){
numBall++;
totalPrice+=unitPrice;
S.O.P("A new ball is generated");
}
int findDiameter(){
return 2*radius;
}
double findVolume(){
return (4.0/3)*Math.PI*Math.pow(radius, 3);
}
44
package p1;
public class testBall {
Box 1
Identify the output when each set of these following statements are put in box1. Write the
outputs. If the statements are invalid, write “invalid”
Statements Outputs
ball1.printBallInfo();
System.out.println(ball1.findVolume());
System.out.println(ball1.findDiameter());
System.out.println(ball1.findAveragePrice());
ball1.color = “Black”;
45
Exercise 4 Identify the output when each set of these following statements are put in
box1. Write the outputs. If the statements are invalid, write “invalid”
package p2;
import p1.Ball;
Box 2
Statements Outputs
ball1.printBallInfo();
System.out.println(ball1.findVolume());
System.out.println(ball1.findDiameter());
System.out.println(ball1.findAveragePrice());
ball1.color = “Black”;
46
Exercises
Inheritance and Constructor chaining
47
Do-It-Together Exercises
48
public class TestBox
{ public static void main(String [] args)
{
}
}
Exercise 1: Identify the outputs when the following sets of statements are put in the box in the
TestBox’s main. If it is invalid, write invalid.
Statements Outputs
Box d1 = new Box(3, 4, 5); Rectangle’s arg constructor
S.O.P(d1.findPerimeter()); Box’s arg constructor
34
49
Exercise 2: Given class Person.
Person(){
System.out.println(“A Person is created”);
}
Person(String name){
this();
this.name = name;
}
void introduce(){
System.out.println(“My name is ”+ name +
“. I am a ” + occupation);
}
Write a class Student as a subclass of Person. The class Student inherits properties and methods
from its superclass. It has two extra properties: String studentID, String schoolLevel.
It has one constructor that takes 3 arguments: String name, String studentID, and String
schoolLevel. The constructor passes two arguments: name and “student” to its super class for
initialization. It sets properties studentID and schoolLevel to the corresponding input arguments.
It has two methods void introduce() and greetNIntroduce(String greeting). The method
introduce() prints output in this format.
My name is name
The second method greetNIntroduce(String greeting) calls the methods greet() of the
superclass and introduce() of its class to printout the output in this format.
greeting
My name is name
50
Complete the Student class.
51
Exercise 3
a. Write a class TestStudent with a main method. In the main method, do following.
i. Create an object Student stu using your name, ID, and schoolLevel (for example
first year).
ii. Call the method greetNIntroduce(“Good Morning”) of stu;
52
Self-Review Exercises
Square(int length){
this.length = length;
S.O.P("A square of edge length" +length+ " is generated");
}
double findArea(){
return length*length;
}
public double findDiagonal(){
return 1.41*length;
}
Cube(int length) {
super(length);
S.O.P("A cube of edge length " +length+ " is generated");
}
double findArea(){
return 6*super.findArea(); //return surface Area
}
Answer
Exercise 2 Identify outputs when each set of the following statements are added into line
7 of the MainTest. Write “no output” if it produces no output or “code is invalid” if it has an
error.
Statement Output
System.out.println(cub1.findArea());
System.out.println(cub2.findArea());
System.out.println(cub1.findPerimeter());
System.out.println(cub2.findPerimeter());
System.out.println(cub1.findVolume());
System.out.println(cub2.findVolume());
System.out.println(cub1.findDiagonal());
System.out.println(cub2.findDiagonal());
54
Exercise 3 Consider the provided classes Pet, Dog, and Bird below. (S.O.P ==
System.out.println)
class Pet {
String ownerName;
String name;
double age;
Pet(){
this.ownerName = "unknown";
this.name = "unknown";
S.O.P("A pet is built from a no-arg constructor");
}
Pet(String ownerName, String name, double age){
this.ownerName = ownerName;
this.name = name;
this.age = age;
S.O.P("A pet is built from an arg constructor");
}
void getInfo(){
S.O.P( name +" "+ ownername+" " + age);
}
void setInfo(String ownerName, String name, int age){
this.ownerName = ownerName;
this.name = name;
this.age = age;
}
55
public class Dog extends Pet {
String type= “dog”;
Dog(){
S.O.P("A dog is built from a no-arg constructor”);
}
------------------------------------------------------
public class Bird extends Pet{
String type="bird";
Bird(){
S.O.P("A bird is built from a no-arg constructor ");
}
Bird(String ownerName, String name, double age){
super(ownerName, name, age);
S.O.P("A bird is built from a 3-arg constructor ");
}
void speak() {
S.O.P(“hungry hungry”);
}
56
Exercise 4 a. Identify outputs when the following statements are executed in the
Main class.
b. identify the output when the following set of statements are put in line 7.
Statements Outputs
p.getInfo();
d1.getInfo();
d2.getInfo();
b.speak();
d1.bark();
d2.speak();
57
Exercise 5 Write UMLs of classes Pet, Dog, and Bird. Show inheritance links between
them.
58
Exercises
Polymorphism
59
Do-It-Together Exercises
Polymorphism
Exercise 1: Identify the outputs from lines 3-8 of the class TestBox
61
Self-review Exercises
Polymorphism
Exercise 1 Use classes Pet, Bird, Dog to identify the outputs of TestPolymorphism
Pet(){
this.ownerName = "unknown";
this.name = "unknown";
}
Pet(String ownerName, String name, double age){
this.ownerName = ownerName;
this.name = name;
this.age = age;
}
public void getInfo(){
S.O.P( name +" "+ ownername+" " + age);
}
public void setInfo(String ownerName, String name, int age){
this.ownerName = ownerName;
this.name = name;
this.age = age;
}
62
public class Dog extends Pet {
String type= “dog”;
Static String color = “brown”;
Dog(){
}
void bark() {
S.O.P(“Bok Bok”);
}
static String print(){
return "I'm a dog";
}
}
------------------------------------------------------
public class Bird extends Pet{
String type="bird";
Static String color = “blue”;
Bird(){
}
Bird(String ownerName, String name, double age){
super(ownerName, name, age);
}
void speak() {
S.O.P(“hungry hungry”);
}
63
1 class TestPolymorphism
2 { public static void main(String [] args]
3 { Bird b1 = new Bird("Jony","Singha",1);
4 Dog d1 = new Dog("Steve","Nestle",3);
5 printInfo(b1);
6 show(d1);
7 checkColor(b1);
8 }
9 static void printInfo(Pet pet)
10 { S.O.P(pet.print());
11 }
12 static void show(Pet pet)
13 { if( pet instanceof Bird)
14 ((Bird) pet).speak();
15 else
16 ((Dog) pet).bark();
17 }
18 static void checkColor(Pet pet)
19 { S.O.P(pet.Color);
20 }
21 static void checkType(Pet pet)
22 { S.O.P(pet.type);
23 }
14 }
64
Exercise 1: Use the classes below to determine validity of the statements.
Square(int length){
this.length = length;
S.O.P("A square of edge length" +length+ " is generated");
}
double findArea(){
return length*length;
}
public double findDiagonal(){
return 1.41*length;
}
public int findPerimeter(){
return 4*length;
}
public static void print()
{ S.O.P("Square”);
}
}
------------------------------------------------------------------------------------------------------------------------
public class Cube extends Square{
int height=length;
Cube() {
S.O.P("A cube of edge length" +length+ " is generated");
}
Cube(int length) {
super(length);
S.O.P("A cube of edge length " +length+ " is generated");
}
double findArea(){
return 6*super.findArea(); //return surface Area
}
65
1 public class Main {
2 public static void main(String[] args) {
3
4 }
5 }
Which of the following is valid when put in line 3 of the class Main.
b. Identify the outputs when each of these statements is put into line 8 of the program. If it
makes the program invalid, write “invalid”.
Statements Outputs
S.O.P(sq.findArea());
S.O.P(sq.findDiagonal());
S.O.P(sq.length);
S.O.P(sq.findVolume());
S.O.P(sq.findPerimeter());
S.O.P(sq.height);
sq.print();
66
Exercises
Abstract and Interface
67
Do-It-Together Exercises
Abstract, Interface
68
Exercise 2. Write a class PartTime that is a subclass of Employee. The class PartTime
has two properties: int numHrPerMo and double hourlyRate.
It has one constructor that takes String name, String position, int numHrPerMo, and
double hourlyRate. The constructor sets the super class’s properties to the input
arguments String name, String position using the keyword super and assigns the
numHrPerMo and hourlyRate to its corresponding properties.
The class PartTime overrides the 1 abstract method of Employee: the double
getPaid() method computes and returns the product of numHrPerMo and hourlyRate. It
has another method void printInfo() calls printInfo() of its super class and adds more
printout statement about the monthly income of the Employee in the format of
Monthly income is XXXX, where XXXX is the value obtained from the call to getPaid().
69
Exercise 3: Assume that the class PartTime in Exercise 2 has been written. Identify the
output.
System.out.println(emp.getPaid());
70
Exercise 2: Consider the interface, abstract classes, and concret classes below.
71
Exercise 3 Complete the definitions of these classes or interface. Leave the method
details with …
Flyer
HomoSapien
Bird
72
Self-Review Exercises
Abstract, Interface
Exercise1 Write the class FullTime that is a subclass of an Employee in the do-it-together
exercises. It has one property: double salary which is initially set to 15000. It has two
constructors. A two argument constructor FullTime(String name, String position) sets name
and position via the keyword super. A three argument constructor: FullTime(String name,
String position, double salary) initializes name and position of the super class using the
keyword super, and also set the property salary to the salary input argument. It has three
methods. void printInfo() which calls printInfo() of the super class and adds a printout
statement that prints out the salary of the FullTime. It also overrides the abstract method
double getPaid() of the superclass and returns the salary of the FullTime.
73
Exercise 2 Consider the following UML
Exercise 1: Write header for each classes, abstract classes, and interfaces.
74
Exercise 3: Complete the definitions for class LivingThing, Animal, and Swan. Leave the
detail of the methods (if needed) with ….
LivingThing
Animal
Swan
75
Exercise 4: Write an interface Vehicle. It has 2 abstract methods: void
printDetailOfWheels() and void printDetailOfPowerSource().
Exercise 5: Write an abstract class Car that is a subclass of interface Vehicle. It has one
property: String typeOfFuel which is initially set to “Diesel”. It has one constructor that has
String typeOfFuel as an input and it sets the property typeOfFuel to the input argument.
The class Car overrides the methods from the interface Vehicle.
It has one non-abstract method: void printTypeOfFuel() which printouts the typeOfFuel
76
Exercise 6: Write a class MPV as a subclass of Car. MPV has no property. It has one
constructor that takes one argument MPV(String typeOfFuel) which sets the typeOfFuel
properties to the input typeOfFuel. It overrides the abstract methods printNumberOfSeats()
from its superclass. It prints out “7 Seats” for this method.
xl7.prinNumberOfSeats();
xl7.printDetailOfWheels();
xl7.printDetailOfPowerSource();
xl7.printTypeOfFuel();
77