0% found this document useful (0 votes)
5 views

DES102 Object-Oriented Programming

The document outlines the course structure for DES102 Object Oriented Programming at Sirindhorn International Institute of Technology, including prerequisites, co-requisites, instructor details, class schedule, and grading schemes. It covers the first half of the course topics, focusing on Java programming concepts such as class components, inheritance, and polymorphism. The teaching style emphasizes hands-on learning through lectures and group exercises, with resources provided via Google Classroom.

Uploaded by

6722790423
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

DES102 Object-Oriented Programming

The document outlines the course structure for DES102 Object Oriented Programming at Sirindhorn International Institute of Technology, including prerequisites, co-requisites, instructor details, class schedule, and grading schemes. It covers the first half of the course topics, focusing on Java programming concepts such as class components, inheritance, and polymorphism. The teaching style emphasizes hands-on learning through lectures and group exercises, with resources provided via Google Classroom.

Uploaded by

6722790423
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 267

Sirindhorn International Institute of Technology

Department of Information, Computer, and Communication Technology (ICT)

DES102 Object Oriented Programming Semester 2, 2024


Pre-requisite: DES/ITS100: introduction to programming
Co-requisite: DES/ITS103: Object Oriented Programming Lab
Following courses: DES/ITS221: Data Structures and Algorithms

Instructor Assoc. Prof. Dr. Pakinee Aimmanee


Office RS-1320 and BKD 3605-2
Tel. 02-501-3505 Ext 3405 (RS) and 5012 (BKD)
Email: [email protected]

Textbook: Introduction to Java by Daniel Liang and a lecture note

Class Time & Place:


Sections 1 and 2: Wed 9:00-12:00 RS1-410
Sections 3 and 4: Thu 9:00-12:00 RS1-410
Sections 5 and 6: Fri 13:00-16:00 RS1-410

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

Topics included in the first half


Topic 1: Class components, basic printout statement, the new
operator, the dot operator
Topic 2: Class components in more detail, Class relationships
Topic 3: Instance and static properties/methods and UML
Topic 4: Visibility modifiers
Topic 5: Inheritance, constructor chaining
Topic 6: Polymorphism
Topic 7: Abstract classes and interfaces

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

• Object Oriented Programming (OOP) is a computer


programming model that organizes software design
around data, or objects, rather than functions and logic.

• Non-Object Oriented Programing or procedural


programming focuses more on instructions.

4
Why we need to learn OOP?

• The OOP provides a systematic structure for programs .

• It is useful for modeling objects and relationships


between them.

• The OOP makes it easy to make extension of objects


from existing objects.

5
Learning OOP through JAVA

• Java is a widely-used language in enterprise software,


Android development, financial systems, and more.

• Java strongly adheres to OOP principles, emphasizing


encapsulation, inheritance, polymorphism, and
abstraction. These features make Java an excellent
language to learn and understand the core tenets of OOP.

• Java's syntax is designed to be clear and consistent, closely


resembling real-world relationships between objects. This
clarity helps beginners grasp OOP concepts more effectively.

• We use JAVA as a medium to study OOP features for this


course.

6
Java History

• James Gosling from Sun Microsystems invented a new


computer language derived from C++ in 1991.
• His language is designed for intelligent consumer-electric
devices.
• “Oak” and “Green” were before named to it. Later, the
name becomes “Java” from the name of the coffee beans
• Java logo is a coffee cup

7
Java Runtime Environment(JRE)

8
JRE Components
• The class loader loads all classes necessary such as
library for the execution of a program

• The Bytecode verifier: to ensure that the code doesn’t


violate system integrity, the code causes no operand
stack overflows or underflows, the parameter type for all
operational code are correct and no illegal data
conversions.

• Interpreter: Java Virtual Machine (JVM) interprets the


codes which are machine dependent

9
Java Virtual Machine (JVM)

• Java Virtual Machine (JVM) is like an interpreter that


provides hardware platform specification

• It can read the compiled byte codes executed from any


platform.

• JVM works in Java runtime environment (JRE), the


environment consisting of many parts that are needed
to run Java application.

10
Objects and Classes

• Object-oriented programming (OOP) involves


programming using objects

• An object represents an entity in the real world that can


be distinctly identified, for example, a student, a desk, a
circle, and a button

• An object has unique properties (identity or attributes),


states, and behaviors

11
How to model an object through simple
descriptions.

• An object has ...


• It can …
• It can be used for …

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

• Actions: What can we do to it or what can it do to


us
– We can compute its area
– We can find its diameter
center

14
Active learning 1: Your object

15
Using Java to model an object
using a Java class’s keyword

16
Classes in Java

• All Java program begins with a keyword “class” which


is always followed by the class’s name, which is
normally an object’s name.

• A class is used to define a template for defining the


object

• Each java file must have an extension java. Ex.


circle.java, cat.java, and desk.java
The “class” keyword is spelled with
a lowercase letter. So it is “class”
not “Class”

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

Some components may be omitted. For


example, one class can have only one
method with no property or constructor.

18
Class Properties

• Define object properties using the class’s variables

• Variable types must be declared to all variables in Java

• Examples of types of variables are int, float, char,


double, String

19
Constructor: a channel to create an object

• A constructor defines how class object should be


created.

• 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

Remark: The program will be written in class by the instructor 23


Object: UnitSquare

1
• Property:
width = 1
1
• Actions:
– Compute the area
– Compute the perimeter

24
Write together: UnitSquare
Written with a no-argument constructor

Remark: The program will be written in class by the instructor 25


Active learning 2: Write a Java class for
your object

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?

• We need a main method.


• The main method is where your program begins executing
and awaits instructions from the user about what to do.
• The program runs line by line in the main method.
• Running a program means telling JRE to load a class file
then start executing codes in the main method until it is
finished.
• The main method must be in a class.

28
The “main” method

• The main method in a class is the method that is


called automatically by JRE.

• It must appear as

public static void main(String [ ] args)

• It is the starting point that the system starts to execute


your program and do something

A class with no main method


cannot run.

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

• The runnable class may be stored separately in a different


file from the object class.
Ex UnitCircle.java and TestUnitCircle.java
UnitCircle.java for defining the object’s contents
TestUnitCircle.java contains a main method that directs
the program's actions using instructional statements.
• Both files need to be in the same package (folder)
• The separation of files make codes clean and more
systematics.

31
Let us create some objects

32
The new Operator

• It is used for creating an instance of object

• The new operator is followed by the constructor’s


name with a proper argument list

To create an instance of UnitCircle, we need to write


new UnitCircle();

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

• The information each variable keeps.

Properties UnitCircle c1 UnitCircle c2

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(); }
}

c1.radius means the radius of c1


c2.radius means the radius of c2
c1.findArea() calls findArea() of c1
c2.findArea() calls findArea() of c2
37
Using the “.” operator
class UnitCircle
public class TestUnitCircle { int radius=1;
{ public static void main(String [] args) UnitCircle( )
{
{ }
UnitCircle c = new UnitCircle(); double findArea()
{ return 3.14*radius*radius;
int c_radius = c.radius;
}
double c_area = c.findArea(); int findDiameter()
{ return 2*radius;
}
} }
}

* Assume that TestUnitCircle.java is in the same location with UnitCircle.java


38
Let us print something out so that we can see

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)

** In this course lecture System.out.println is shorten as S.O.P **

• System.out.print(arg) prints arg without adding any newline

40
String

• Use “ ” to denote String such as “answer =”


• + for concatenation
String + String → String
String + number →String

Ex. String A = “Hello”;


String B = “World”;
int C = 123;
System.out.println(A+B); → HelloWorld
System.out.println(A+B+C); → HelloWorld123

41
The + operator

• Addition
int x = 2, y =3;
int z = x + y;

• Concatenation between String and number


double pi = 22.0/7;
S.O.P(“The approximate value of pi is” + pi);

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(); }

double c_area = c.findArea();


System.out.println(“The area of c is ”+ c_area);
}
Properties UnitCircle c
}
radius

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;
}
}

// printout the area of s

}
} 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( ) }

{ name = “Bob Schneider”;


salary = 18750.25;
dob = new Date(1, 1, 2000); We say that
gender = ‘m’; Person has dob,
which is of type
} Date, as one of
} the properties.

52
* Assume that Person.java is in the same location with Date.java
class Person

Identify the { String name;


int age;
output double salary;
Date dob;
class TestPerson
boolean married;
{ public static void main(String [] args) char gender;
{ Person p = new Person(); Person(){
name = “Nick Cage”;
S.O.P(p.name); age = 25;
S.O.P(p.age); salary = 15783.50;
dob = new Date(1, 1, 2000);
S.O.P (p.salary); gender = ‘m’;
S.O.P (p.dob.day); }
}
S.O.P (p.dob.month);
S.O.P (p.dob.year); class Date{
int day;
S.O.P (p.married); int month;
int year;
S.O.P (p.gender); Date (int d, int m, int y)
} { day = d;
month=m;
} year = y;
}
}
* Assume that all these classes are in the same location
53
Objects’ profiles

Properties Person p Properties Date dob


String name int day
int age int month
double salary int year
Date dob
boolean married
char gender

54
Constructors

• Constructors are commonly used to construct


an instance of an object with user-defined properties. It can
also be used to do tasks upon object construction.

• It must have constructors, name as the class name

• The constructors must have no return type.

• A class can have no constructor at all.

• A class can have multiple constructors, but they must not


have the same list of argument types

55
Types of Constructors

1. No argument constructor: constructor without


argument. The initial values of the properties will be used.
If the properties are not initially set, the default values are
used.
2. Argument constructor: constructor with arguments
3. No-show constructor: is provided by JRE when a
class has no constructor. This type of constructor has no
argument and has empty content.

* We use arg as an abbreviation of argument

56
class Point with a no-arg constructor

class Point class TestPoint


{ public static void main (String [] args)
{ int x = 3; {
int y = 4 ; Point p = new Point( );
S.O.P(p.x);
Point( ) S.O.P(p.y);
{ x = 0; }
}
y = 0;
} Properties Point p
} int x
int y

* Assume that TestPoint.java is in the same location with Point.java 57


Ex. class Point with a 2-argument constructor

class Point class TestPoint


{ int x= 3; { public static void main (String [] args)
int y= 4; {
Point(int a, int b) Point p = new Point(1, 2);
{ x = a; S.O.P(p.x);
y = b; S.O.P(p.y);
}
}
}
}
Properties Point p
int x
int y

* Assume that TestPoint.java is in the same location with Point.java 58


Ex. class Point with two constructors

class Point class TestPoint


{ int x = 3 ; { public static void main (String [ ] args)
{ Point p1 = new Point(5, 6);
int y = 4; Point p2 = new Point();
Point (int a, int b) S.O.P(p1.x);
{ x = a; S.O.P(p1.y);
S.O.P(p2.x);
y = b; S.O.P(p2.y);
} }
Point( ) }
{ x = 0; Properties Point p1 Point p2
y = 0; int x
} int y
}
* Assume that TestPoint.java is in the same location with Point.java 59
Ex. class Point with no constructor

class Point class TestPoint


{ int x=3; { public static void main (String [] args)
{ Point p = new Point( );
int y=4;
S.O.P(p.x);
S.O.P(p.y);

}
}
}
Properties Point p
int x
int y

* Assume that TestPoint.java is in the same location with Point.java 60


Why does TestPoint get a compilation error when
run?
class Point class TestPoint
{ public static void main (String [ ] args)
{ int x = 3 ; {
int y = 4; Point p2 = new Point();
S.O.P(p2.x);
S.O.P(p2.y);
Point (int a, int b) }
{ x = a; }

y = b;
}
}

* Assume that TestPoint.java is in the same location with Point.java 61


Class’s Methods

• Methods are program functions that define the


behaviors of the object.
• A class can contain no method or multiple methods.
• Methods can be overloaded. i.e. they are allows to
have the same name but different parameter lists.
Ex. int B(int x, String y) {…}
void B(String y) {…}
The Java compiler determines which method is used
based on the method signature.

62
Defining a Method
• The syntax for defining a method is as follows
returnType methodName(list of parameter)

Ex. void printMax(int num1, int num2)


{ if (num1 > num2)
System.out.println(“Max is ” + num1);
else
System.out.println (“Max is ”+ num2);
}

• A method can use properties or use other methods in the


same class
63
Facts about methods

• A method can access properties within the same


class.

• A method can access other methods within the same


class.

• An object can be passed to a method. If there is any


modification made to the object’s properties, it
permanently affects the object’s properties.

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) { }

for(int i=0; i < t ; i=i+1)


{S.O.P(“Hello”); }
}
void Hello(String name) {
S.O.P(“Hello”+ name);
} 65
A change made to the object through a method

class Demo class Circle


{ static void unifyRadius(Circle c) { int xcenter;
{ c.radius=1.0; int ycenter;
double radius;
}
Circle(int x, int y, double r)
public static void main(String[] args)
{ xcente= x;
{ Circle a = new Circle(1, 2, 3.0); ycenter = y;
Circle b = new Circle(4, 5, 6.0); radius = r;
S.O.P (a.radius); }
S.O.P (b.radius); double findArea()
unifyRadius(a); { return 3.14*radius*radius;
unifyRadius(b); }
double findDiagonal()
S.O.P (a.radius);
{ return 2*radius;
S.O.P (b.radius);
}
} }
}
* Assume that Demo.java is in the same location with Circle.java 66
Constructor chaining

A widely used technique where one constructor calls


another constructor to improving code reusability.

67
Using the this keyword to call another
constructor

To use this to refer to another


constructor, the call must be the
first statement in the
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

• The keyword this can not only be used to call another


constructor, but it can also differentiate between input
arguments and class properties when they have the same
name.

71
class Circle {
int xcenter; An example of the use of
int ycenter; the keyword this
double radius;

Circle(int xcenter, int ycenter, double radius)


{ this.xcenter = xcenter;
this.ycenter = ycenter;
this.radius = radius;
}
Circle( ) { this(0, 0, 1.0); }
Circle(double r) { this(1, 2, r); }

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

• Static variables and methods can be used from


both instance or static methods in the class. As
they are class’s mutual variables and methods,
they can also be accessed through the class
name.

• Instance variables and methods can be used only


from instance methods, not from static method

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;
}
}
}
}

* Assume that TestChild.java is in the same location with Child.java 78


Accessing static variables/methods

Can be done in two different ways:


1. From object as usual.
Ex. From previous examples
jill.money, jill.payMoney()
jack.money, jack.payMoney()
c1.circleCount, c2.circleCount, c3.circleCount

2. Directly from the class name (preferred one)


Ex. From previous examples
Child.money, Circle.circleCount

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;

Circle( ) { this(0, 0, 1.0); }


Circle(int xcenter, int ycenter, double radius)
{ this.xcenter=xcenter;
this.ycenter=ycenter; The static variable CircleCount is
this.radius=radius; shared in all instances of Circle.
CircleCount++; This means all instances of Circle
} will have a unique value of
Circle(double r) CircleCount.
{ this(0, 0, r);
}

double findArea() { return radius*radius*3.14; }


double findDiameter(){ return 2*radius; }
}
81
Identify the outputs class Circle {
int xcenter;
class TestCircle int ycenter;
{ public static void main(String [] args) double radius;
{ Circle c1 = new Circle(); static int CircleCount=0;
S.O.P(c1.xcenter); Circle( ) { this(4, 2, 1.0); }
S.O.P (c1.ycenter);
Circle(int xcenter, int ycenter, double radius)
S.O.P (c1.radius);
{ this.xcenter=xcenter;
S.O.P (c1.CircleCount);
this.ycenter=ycenter;
Circle c2 = new Circle(1, 2, 3.0); this.radius=radius;
S.O.P (c2.xcenter); CircleCount++; }
S.O.P (c2.ycenter); Circle(double r) { this(0, 0, r); }
S.O.P (c2.radius); double findArea() { return radius*radius*3.14; }
S.O.P (c2.CircleCount); double findDiameter(){ return 2*radius; }
}
Circle c3 = new Circle(2.0);
S.O.P (c3.xcenter); Properties/methods Circle c1 Circle c2
S.O.P (c3.ycenter);
S.O.P (c3.radius); int xcenter
S.O.P (c3.CircleCount);
int ycenter
S.O.P (c2.CircleCount); double radius
S.O.P (Circle.CircleCount);
} double findArea()
}
double findDiameter
int circleCount 82
Example:
class Person
{ String name;
Invalid call to a non-static
static int numPerson=0; property from a class name
Person(String name) {
class TestPerson
this.name=name;
{ public static void main(String [] args)
numPerson++;
{ S.O.P(Person.name);
}
}
void introduce()
}
{ S.O.P(“Hello, nice meeting you”);
}
static void greeting() { S.O.P(“Hello”);
}
}

Calling a non-static property from


the class name causing the
compilation error.

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”);
}
}

Calling a non-static method from the


class name causing the compilation
error.

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)

• UML is a standard way to represent the class’s skeleton.

• It is represented with a table of 3 rows


– The first row: title
– The second row: properties
– The third row: constructors and methods

• For variables/methods, the variable/method name is written


first, then its type

• UML notations for properties/methods


static underline ________

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.

• To learn visibility modifiers: private, default, and public to be


used to mark the scope of data accessibility.

94
A package in Java

• A package is a namespace that organizes a set of


related classes and interfaces.
• Conceptually we can think of packages as folders on
our computer.
• We learn how a class protects its components for
being accessed/modified in different locations: in the
class, in the package, and outside the package

95
Encapsulation

• The concept of protecting a variable from being directly


modified is called encapsulation.

• When the programmer would like to allow the users to


access the encapsulated variables, he/she opens a new
channel with higher visibility to allow the users to use it.

96
Visibility Modifiers

• Visibility modifier is a word putting in front of the


class, properties, constructor, or methods to indicate
the scope of visibility.
• public, protected, and private are visibility modifier.
• Java organizes files into groups according to their
functionality using package

97
Summary of visibilities

Visibility Scope of classes, methods, and properties UML


notation
public accessible from any class on any package +

protected accessible from any class on the same package #


or outside of the package for its subclass

default accessible only from within the same package (empty)

private accessible only from within it’s own class -

98
The Import keyword

• The import package declares a used Java class defined


in other package
• Once a Java class is declared, then the class name can
be used in the code without specifying the package the
class belongs to.
• The import is written before the class scope.
• Syntax import [package name].[class’s name];
• We can use the '*' character to declare all the classes
belonging to the package.
Ex. import p1.circle;
import javax.swing.*;

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?

• There is no way for a user to access private


properties/methods directly unless the class’s owner
provides a channel with a wider scope to access such
private properties/methods.

• In the previous example, radius can’t be accessed


anywhere else outside the class.

• If we are the owner of the Circle.java, we can add a


method getRadius() with a higher visibility than private to
allow the data to be accessed in the scope that we want .

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:

• To learn the inheritance concept


• To learn how to extend a class in Java
• To learn how a subclass inherits
properties/methods from its superclass
• To learn how the keyword super works
• To learn about the constructor chaining
behavior

107
Inheritance

• Inheritance is the main feature in Object-oriented


programming that allows one class to derive
properties or methods from an existing class.

• Every class you define in Java derives from an


existing class called Object which is in java.lang
package.

We can say that Object is


the ancestor of all classes.

108
Circle Vs Cylinder

Circle Circle Cylinder


properties xcenter xcenter
ycenter ycenter
radius radius
Height
methods findArea() findArea()
findDiagonal() findDiagonal()
findVolume()
findSurfaceArea()

109
Super Class and Subclass

• A superclass is a class that is derived from


another class. It is also called a parent class or a
base class

• A subclass is a class that derives from an existing


class. It is also called a child class.

• In the above illustration, we say


Circle is a super class of Cylinder.
Cylinder is a subclass of Circle

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,

Super class Sub classes


A square A box
A house’s window
A circle A cylinder
A clock
A pencil A mechanical pencil
A electronic pencil

111
Active learning 6: Thinking of other pairs of super
class-sub class

112
“extends” and “super”

• The keyword extends is used for indicating that the class


derives from an existing class
• The keyword super can also be used with a dot operator on
a property and a method to mean that of the superclass.
• The keyword super invokes the constructor of the
superclass to initially set the properties value.
• When a call to the superclass constructor is omitted, the
subclass automatically calls a default constructor of a
superclass (super() is called).
• The call-to-super statement must appear in the first line in
the subclass constructor.
• We can use super(…) as well this (…) only once inside a
constructor.
113
Inheritance Rules
• The non-private properties or methods in the super
class can be accessed directly by super.method and
super.property.

• A subclass can access all non-private properties and


non-private methods from the super class.

• A super class cannot access any properties and


methods of the subclass.

114
Inheritance rules…cont.
• The caller can access the properties and the methods of
the super class via subclass’s instance.

• Each subclass can only have one single super class.

• Inheritance makes a one child one- one mother


relationship.

• However, each super class can have multiple subclasses.

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( );
}
}

Properties Cylinder cyl1 Cylinder cyl2


inherited own

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

• The subclass can have method having the same name


with its super class. The content of such a method can
differ from that of the parent class.

• We say that the subclass overrides the method of the


super class.

• Note that the method that is overridden in the super


class must not be private.

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());
}
}

Properties Cylinder cyl


double height 2.0
int xcenter 0
int ycenter 0
double radius 1.0
123
Omitting the call to super in a subclass as a
default case

124
Default super

• The imaginary super or the default super (super()) will be


automatically assumed if the user does not provide one,
ensuring that the subclass inherits all non-private
properties from the superclass.

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.

• This can be done when there is no properties or methods


of the same name in the subclass.
• When a method or a property is accessed, the system
looks for the local one first. If it cannot find it, it will keep
looking from its super class, super’s super class, …until
reaching the top of the family tree.

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?

Yes! We can mark a class


with a keyword “final”
to prevent it from being
inherited.

130
The “final” keyword

• When it is placed in front of a class definition, it


prevents a class from being extended

• When it is placed in front of a variable, it prevents a


variable from being modified (it becomes a constant)

• When it is placed in front of a method, it forces the


method not to be overriden by the subclass

131
Use final to prevent a class from being derived
by other class

final class Mother Trying to derive from a final class


{… causes compilation error.
}
-------------------------------------

class Child extends Mother


{…
}

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;

from being Cylinder() { super();


height=1.0; }
overridden Cylinder(int x, int y, double r, double height)
class Circle { { super(x, y, r);
int xcenter=0; this.height=height;
int ycenter= 0; }
double radius=1.0; Cylinder(int height){ this.height = height; }
static int circleCount=0; double findArea() {
Circle() {circleCount++;} return 2*super.findArea() +
Circle(int x, int y, double r) 2*Math.PI*getRadius()*height;
{ xcenter = x; }
ycenter = y; double findVolume()
radius = r; { return super.findArea()*height;
circleCount++; }
} }
double getRadius() { return radius; }
final double findArea() { return 3.14*radius*radius; }
double findDiameter(){ return 2*radius;}
}
The method findArea() is final, this
means its content cannot changed in its
subclasses. This causes a compilation
error in the class Cylinder 134
Visibility modifier “protected”

• The protected visibility can be used to mark the


variables or methods in the super class that the user
wants them to be accessed in the subclass even
though the subclass is in different package

• In uml, # is used to represent protected variable

Easy speaking, protected


is default + subclasses in
any package

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

• An OOP technique where one constructor calls another


to centralize initialization logic, improving code
reusability.
• It is a chain of callings to super classes from
subclasses.
• It occurs when we have multiple levels of inheritance
• The subclass always calls the constructor of the super
class via keyword super.
• The primary use is to make a program simpler, with
fewer repeated line of codes.

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”;

FoodCan(double radius, double height, String food)


{ super(radius, height) ; Circle
this.food = food;
S.O.P(“3-arg constructor of FoodCan”);
}
FoodCan(String food) Cylinder
{
this.food= food;
}
FoodCan
void printLabel()
{ S.O.P(food+ “ can”);
}
}
144
Identify the outputs when class TestConstructor
each of these statements is { public static void main(String [] args)
{
put to the main method of
TestConstructor }
}

• Cylinder cyl1= new Cylinder(1, 2 ,3.0, 4.0);

• Cylinder cyl2= new Cylinder(5.0, 6.0);

145
class TestConstructor
{ public static void main(String [] args)
{
• Cylinder cyl3= new Cylinder(7.0);
}
}

• Cylinder cyl4= new Cylinder();

146
class TestConstructor
{ public static void main(String [] args)
Identify the outputs {

}
}

• FoodCan fc1 = new FoodCan(“Nut”);

• FoodCan fc2 = new FoodCan( );

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

• Polymorphism is the concept that one instance can be


referred as the super class’s instance

• We can convert an object of one class type to another


within an inheritance hierarchy.
Ex. Circle C = new Cylinder(0, 0, 1.0, 2.0);
We may say that C is created as a Cylinder but has type
Circle.

• We call a variable that can hold values of different types


during the course of execution a polymorphic variable.
150
Polymorphism Analogy

Fruit class Fruit {


Fruit() {…}
}

Apple class Apple extends Fruit {


Apple(){…}
}

Fuji class Fuji extends Apple{ …


Fuji(){…}
}

151
Implicit Casting

• Like it is normal to say “an apple is a fruit”, an object in


Java can be created with a subclass type and be
referenced as a superclass type.

• This is called Implicit Type Casting, a conversion of


types without losing its original meaning
Circle C = new Cylinder(0, 0, 1.0, 2.0);
Fruit f2 = new Apple();
Apple f3 = new Fuji();
Fruit f4 = new Fuji();

152
Down casting
• A polymorphic variable can be casted back to it created
type by adding (subclasstype) in front of the variable
name.

Circle cc = new Cylinder(0, 0, 1.0, 2.0);

By writing (Cylinder) cc, this will make a compiler see a


variable cc as a Cylinder rather than a Circle

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;

• Direct explicit casting yields compilation errors


Ex. Fuji fu1 = new Apple();
Apple ap = new Fruit();
Fuji fu2 = new Fruit();
Cylinder x = new Circle();

154
instanceof Operator

• Because a superclass-type variable can come from many


subclass-types creation, we can use the operator
instanceof to check whether it is a form of its subclass.

• The instanceof operator take two operands: frontOperand


and backOperand. It returns true if the frontOperand is an
instance of backOperand, and returns false otherwise.

Note that instanceof is


spelled in one word. Not
“instance of”.

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);

The following statements print false


System.out.print (f1 instanceof Circle);
System.out.print (f2 instanceof Fuji);

156
Early binding VS Dynamic Binding

• Polymorphism allows an object to take multiple forms –


when a method exhibits polymorphism, the compiler has
to map the name of the method to the final
implementation.

• If it's mapped at compile time, it's a static or early binding.


If it's resolved at runtime, it's known as dynamic
or late 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?

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; }
} }
}

158
Whose method to be used for
a polymorphic variable

The method appears in both super class and subclass?

Yes No

Are both methods static? Where the method is located in?

Super class Sub class


Yes No

Use superclass’s Use subclass’s Use superclass’s Compilation Error!

159
Whose property to be used for a
polymorphic variable

The property appears in both super class and subclass?

Yes No

Are both properties static? Where the property is located in?

Super class Sub class


Yes No

Use superclass’sUse superclass’s Use superclass’s Compilation Error!

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.

Ex. Circle cc= new Cylinder(0, 0, 1.0, 1.0);


cc.findVolume() ; will give you an error because the
findVolume method is defined only in Cylinder which cc
doesn’t allow to use.

(Cylinder) cc will tell the compiler that cc is a Cylinder

((Cylinder) cc). findVolume() will call findVolume() of


Cylinder without any problem.

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

• Abstract objects cannot have any specific instances

• Examples of abstract objects


– Feelings: sadness, happiness, love, courage, patience
– Concepts: government, human, animal, education, shape

166
Ex Sadness

• Properties: cause, level, type

• Methods: get medicine, find cause, find therapist

167
Abstract Classes

• Sometimes a super class is so abstract that it is cannot


have any specific instances. Such a class is referred to
as an Abstract class.

• It has a keyword abstract before the keyword class

168
Abstract class’s s components

• An abstract class can define abstract properties.


• An abstract class can have constructors.
However, these constructors serve to define the
parent class for other classes but do not
facilitate the instantiation of an object.
• It can have usual methods (concrete methods)
and also a special kind of method so-called an
abstract method. The abstract method always
ends with a semicolon (;). The body is provided
by the subclass (inherited from).

169
Example: Two dimensional shape

• Properties: number of sides


• Methods: print the abstract type name, find its area, find
its perimeter

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());
}
}

Properties Cylinder cyl


double width 3.0
double length 4.0
int numSides 2

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

Another way to define abstract objects.

176
Interface Vs Abstract class
• They both can be used to model an abstract object.

• An interface comprises pure abstract methods, whereas


An abstract class comprises partially abstract methods.

• The advantage of interfaces over abstract classes is that a


class can have multiple interface parents, while it can have
only one abstract parent.

• Java uses the keyword interface to distinguish it from a class.

177
Interfaces

• An interface is a class-like structure that contains only constant


variables and abstract methods, which can be accessed
anywhere (public).

• Also, since the interface is known by its definition to contain


only the constants and the abstract methods, the keyword
abstract in front of the method may be omitted.

• The modifier public marked in front of constant variables and


abstract methods in the interface can also be omitted as it is
assumed by the system that they are all public.

178
Interface …continue

• Variables in an interface must be public, static, and final.


This makes variables of the interface a unique constant
(unchangeable) and can be accessible anywhere.
• An interface does not contain any constructors
• An interface cannot be instantiated using the new
• An interface is not extended by a class, it is implemented
by a class

179
Abstract object Edible

• Print how to eat


• Print type (for example, meat, vegetable, fruit)

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

Banana •The + sign indicates public


modifier
tellHowToEat(): String
printType(): String

182
When a class derives from an interface

• When a class derives a parent which is interface, we


use the keyword implements instead of extends.
• A class can derive from multiple interfacial parents.
• The comma (,) is used for listing interfacial parents
• A non-interfacial parent must be listed before interface
parents
• Parent listing format is
class [class name] extends [a non-interfacial parent]
implements [interfacial parents]

183
Defining a class with abstract or interface parents

<interface> <interface>
Animal
Vehicle Flyer

Airplane Bird

class Airplane implements Vehicle, Flyer


{…
}
class Bird extends Animal implements Flyer
{
}
184
Example1: classes and interfaces
class Orange extends Fruit implements
interface Edible Edible
{ public String howtoEat(); { String howToEat()
public String printType(); { return “Make orange juice”;
} }
double CalculateVitC( )
interface Animal { { return 75.28;
public void eat(); }
public void move(); }
} class Chicken implements Animal, Edible
{ public String howToEat()
abstract class Fruit implements Edible { return “Make fried chicken”;
{ abstract double calculateVitC( ); }
public String howToEat() { public String printType() {return “meat”; }
return “Make Juice”; public void eat() { S.O.P(“Peck grains”); }
public void move() { S.O.P(“Walk”); }
}
}
public String printType(){
return “Fruit”;
}
185
}
Example: Interface ActionListener

interface ActionListener {
public void actionPerformed(ActionEvent e);
}

----------------------------------------------

class myFrame implements ActionListener


{ public void actionPerformed(ActionEvent e)
{ System.out.println(“ActionEvent is detected”);
}
}
186
Active learning 9: Trace a code on problems with
abstract classes and interfaces

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

The Bicycle program

class Bicycle {
int cadence = 1;
int gear = 2;
int speed = 0;

Bicycle()
{
}

void setCadence(int newValue)


{ cadence = newValue;
}

void setGear(int newValue)


{ gear = newValue;
}

void applyBrake(int decrement)


{ speed = spped-decrement;
}

void speedUp(int increment)


{ speed = speed+increment;
}

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

and length is preset to 2. Width=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.

public class TestRectangle

{ public static void main(String [ ] args)

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()
{
}

String getName(){ return name; }

void setName(String newName){ name = newName; }

double getBalance() { return balance; }

void setBalance(double newBalance){


balance = newBalance;
}

void quickWithdraw()
{
balance = balance – 1000;
}

void withdraw(double amount)


{
String message = “amount exceeds balance”;
if (amount > balance)
System.out.println(message);
else
balance = balance-amount;
}

void deposit(double amount)


{ balance = balance + amount;
}

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.

ownerName accountNumber balance

public class BankAccount {

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

Lisa Blackpink, 091-456-7856, and 200000.00, respectively.

• Call the deposit method of bacc to deposit 30000.75 to bacc.


• Call the printInfo method of bacc to see print the current account details.
• Call the withdraw method of bacc to withdraw 20000.50 from the bacc.
• Call printInfo of bacc again to see the current account details.

12
Exercise 8: Identify the output when the class TestBankAccount is run.

13
Exercises
Class components in more detail

14
Do-It-Together Exercises

Class components in more detail

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.*; }

class MessagePanel extends JPanel int getInterval() {


{ String message = "Welcome to Java"; return interval;
}
int xCoordinate = 20;
void setInterval(int interval) {
int yCoordinate = 20; this.interval = interval;
repaint();
boolean centered; }

int interval = 10; void paintComponent(Graphics g) {


super.paintComponent(g);
MessagePanel() { if (centered) {
} x = (getWidth()-10) / 2;
y = (getHeight() + 20 )/2;
MessagePanel(String message) { }
this.message = message; g.drawString(message, x, y);
} }

String getMessage() { void moveLeft() {


return message; xCoordinate -= interval;
} repaint();
}
void setMessage(String message) {
this.message = message; void moveRight() {
repaint(); xCoordinate += interval;
} repaint();
}
int getXCoordinate() {
return xCoordinate; void moveUp() {
} yCoordinate -= interval;
repaint();
void setXCoordinate(int x) { }
this.xCoordinate = x;
repaint(); void moveDown() {
} yCoordinate += interval;
repaint();
int getYCoordinate() { }
return yCoordinate;
} Dimension getPreferredSize() {
return new Dimension(200, 30);
}
void setYCoordinate(int y) {
this.yCoordinate = y; }
repaint();
}

15
Exercise 2: Consider the class Dog below. Circle and label parts that are properties, constructors,
and methods.

class Dog

{ String name = “Wat”;


String owner = “Luangta”;

Dog()
{ System.out.println(“In a no-arg constructor”);
}

Dog(String name)
{
this.name = name;
System.out.println(“In a 1-arg constructor”);

Dog(String name, String owner)


{ this(name);
this.owner = ownwer;
System.out.println(“In a 2-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();
}

void perform(int times)


{ for( int i=0; i< times; i++)
perform();
}
}

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

Line Number Output


8

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 ; }
}

public class TestRectInSpace


{ public static void main(String [] args)
{

RectInSpace rs1 = new RectInSpace();

Point p = new Point(1, 2);

RectInSpace rs2 = new RectInSpace(p, 3, 4);

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

Class Components in more detail

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”);
}

Person(String name, String occupation){


this.name = name;
this.occupation = occupation;
S.O.P(“A Person is created”);
}

void introduce(){
S.O.P(“My name is ”+ name + “. I am a ” + occupation);
S.O.P(“Nice to meet you”);

void introduce(String greeting){


S.O.P(greeting);
introduce();
}
}

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 2 constructors: a 2-argument constructor and a 4-argument constructor. The


2-argument constructor takes Name name, and StudentID studentID as inputs and uses
them as properties for name and studentID. The 4-argument constructor takes Name
name, String studentID, Date dateOfBirth, and String department as inputs. It uses the this
keyword to call a 2-argument constructor that takes name and studentID as an input for
initializing the properties name and studentID, and assigns dateOfBirth and department
inputs to its corresponding properties.

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

Name: firstName lastName

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.

1. Construct a name object namely myName from your name


2. Construct a Date object namely myDOB from your date of birth
3. Construct a studentID object namely myID which uses myName, ID, myDOB, and
address.
4. Make a student ID Card by calling makeCard() of myID.

Exercise 7: Identify the output when TestStudentID is run.

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");
}

Pet(String name, String type)


{ this(name);
this.type=type;
S.O.P("In a 2-arg constructor");
}

Pet(String name, String type, int age)


{ this(name, type);
this.age=age;
S.O.P("In a 3-arg constructor");
}

Pet(String name, String type, int age, double weight)


{ this(name, type, age);
this.weight = weight;
S.O.P("In a 4-arg constructor");
}

boolean isHeavier(Pet pet2)


if(weight > pet2.weight)
return true;
else false;
}
boolean isOlder(Pet pet2)
if(age > pet2.age)
return true;
else false;
}
}

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

1 public class Testpet


2 { public static void main(String[] args)
3 { Pet pet1 = new Pet(“Maggy”);
4 Pet pet2 = new Pet("Garfield","Cat", 3, 8.5);
5 Pet pet3 = new Pet("Shisu", "Dog");
6 Pet pet4 = new Pet("Tomo","Bird", 2);
7 S.O.P(pet1.isHeavier(pet2));
8 S.O.P(pet2.isHeavier(pet3));
9 S.O.P(pet3.isOlder(pet4));
10 S.O.P(pet4.isOlder(pet1));
11 }
12 }

Line number Output


3

10

28
Exercises

Static and UML

29
Do-It-Together Exercises
Static properties/method, UML

Exercise 1 Consider the Rectangle class below.


a) Mark and label all static properties and methods.
class Rectangle {
double width;
double height;
double area;
static int numRectangle;
static double totalArea;

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");
}

Rectangle (double width, double height){


this.width = width;
this.height = height;
area = findArea();
numRectangle++;
totalArea = totalArea +findArea();
System.out.println("A 2-arg constructor is called");
}
double findArea()
{ return width*height;
}

double calculateCost(){

if(area < 5){


return area*20;
}
else if(area < 10){
return area*15;
}
else{
return area*10;
}
}

static void printCumulativeArea(){


System.out.println("The cumulative area of " +
numRectangle +
" rectangle(s) = " + totalArea);
}

30
}

b) Writing a UML diagram for the class Rectangle defined in part a).

31
Exercise 2 Identify the outputs

1 public class TestRectangle


2 { public static void main(String[] args) {
3 Rectangle rec1 = new Rectangle(3.0);
4 Rectangle rec2 = new Rectangle(4.0, 5.0);
5 new Rectangle();
6
7 System.out.println(rec2.totalArea);
8 System.out.println(rec1.area);
9
10 Rectangle.printCumulativeArea();
11
12 }
13 }

Line no. Output


3

10

32
Self-Review Exercises

Static keyword, UML

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 length, int width, int height)


{ this.length = length;
this.width = width;
this.height = height;
noOfPyramid++;
System.out.println("Created from a 3-arg constructor");
}

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;
}

static int findNoOfPyramid(){


return noOfPyramid;
}

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.

public class Ball {


int radius = 1;
String color= "red";
float unitPrice = 100.00;
static int numBall;
static float totalPrice;

Ball(){
numBall++;
totalPrice+=unitPrice;
System.out.println("A new ball is generated");
}

Ball(int radius, String color, float price){


this.radius = radius;
this.color = color;
unitPrice = price;
numBall++;
totalPrice= totalPrice + unitPrice;
System.out.println("A new ball with radius "+ radius +
" 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);
}

static float findAveragePrice(){


return totalPrice/numBall;
}

37
b) Write the UML of class Ball

38
Exercise 5 Identify outputs when the following program is executed.

1 class TestBall

2 { public static void main(String[] args) {

3 Ball b1 = new Ball();


4 Ball b2 = new Ball(5,"Green", 1000.0);
5 new Ball(10, "Yellow", 800.25);
6 Ball b3 = new Ball(7,"Black", 700.50);
7
8 System.out.println(Ball.numBall);
9 System.out.println(Ball.findAveragePrice());
10 }
11 }

Line number Output

39
Exercises
Visibility Modifiers

40
Do-It-Together Exercises

Visibility modifiers

Exercise 1: Consider the following program


package p1;
package p1; public class TestDogInP1
public class Dog { public static void main(String [] a)
{ static int numDog=0; { Dog d1 = new Dog(“Odie”, “Sue”);
private String name;
String owner;
Box1
public Dog(String name,
String owner ) }
{ this.name= name; }
this.owner=owner;
numDog++;
} package p2;
public Dog() import p1.Dog;
{ this(“Boonlong”, “none”);}
static void bark() public class TestDoginP2
{ S.O.P(“Bok Bok”); } { public static void main(String [] a)
void howl() { Dog d2 = new Dog(“Google”, “DJ”);
{S.O.P(“Arooo”); }
String getName() Box2
{ return name;}
}
public String getOwner() }
{return owner;}
public void setOwner(String owner)
{ this.owner=owner;
}
}
Identify whether it is valid or invalid. If invalid, explain the reason.
Statements Valid Invalid (provide explanation)

d1.name= “Whisky”; is put in Box1 x

d1.owner= “Patty”; is put in Box1 x

S.O.P(d1.numDog); is put in Box1 x

d1.setOwner(“Sue”); is put in Box1

d2.name = “Zimba”; is put in Box2 x

d2.howl(); is put in Box2 x

S.O.P(d2.getName()); is put in Box2 x

S.O.P(d2.getOwner()); is put in Box2 x

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;

public class BankAccount {


String ownwerName;
String accountNumber;
double balance;
int numAccount=0;

BankAccount(String ownerName, String accountNumber,double balance)


{ this.ownwerName=ownwerName;
this.accountNumber=accountNumber;
this.balance=balance;
numAccount++;
}

void deposit(double amount){ balance = balance + amount; }


void withdraw(double amount)
{ if(balance>amount)
balance = balance-amount;
else
S.O.P("Not enough balance!");
}

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;
}
}
}

Remark: S.O.P = System.out.println

Determine whether the following statements are valid or Invalid.

Statements Invalid Valid

rt1.base= 3; is put in Box1 x

rt1.height= 6; is put in Box1 x

S.O.P(rt1.count); is put in Box1 x

S.O.P(rt1.getHeight()); is put in Box1 x

rt2.base = 8; is put in Box2 x

rt2.findDiagonal(); is put in Box2 x

S.O.P(RightTri.count) is put in Box2 x

S.O.P(rt2.findArea()); is put in Box2 x

S.O.P(rt2.count); is put in Box2

43
Exercise 3: Consider the following program.

package p1;

public class Ball {


int radius=1;
private String color= "red";
float unitPrice=100;
static int numBall;
static float totalPrice;

Ball(){
numBall++;
totalPrice+=unitPrice;
S.O.P("A new ball is generated");
}

Ball(int radius,String color, float price){


this.radius = radius;
this.color = color;
unitPrice = price;
numBall++;
totalPrice= totalPrice + unitPrice;
S.O.P("A new ball with radius "+ radius +
" is generated");
}

int findDiameter(){
return 2*radius;
}

double findVolume(){
return (4.0/3)*Math.PI*Math.pow(radius, 3);
}

private void printBallInfo(){


S.O.P("Ball radius: "+radius+" Color: "
+ color+" Price: " + unitPrice);
}

static float findAveragePrice(){


return totalPrice/numBall;
}

44
package p1;
public class testBall {

public static void main(String[] args) {

Ball ball1 = new Ball(5,"GREEN", 2000);

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;

public class testBall {

public static void main(String[] args) {

ball_1 = new Ball(5, "WHITE", 2000);

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

Inheritance, Constructor chaining

Consider the following programs.

public class Rectangle


{ int width;
int length;
Rectangle( )
{ this(1, 2);
S.O.P(“Rectangle’s no-arg constructor”);
}
Rectangle(int width, int length)
{ this.width=width;
this.length=length;
S.O.P(“Rectangle’s arg constructor”);
}
int findArea() {
return width*length;
}
int findPerimeter() {
return 2*(width + length);
}
}
-------------------------------------------------------------------------------------------------------
public class Box extends Rectangle
{ int height=3;
Box(int width, int length, int height)
{ super(width, length);
this.height=height;
S.O.P(“Box’s arg constructor”);
}
Box()
{
S.O.P(“Box’s no-arg constructor”);
}
int findVolume() {
return findArea()*height;
}
int findPerimeter() {
return 2*super.findPerimeter()+ 4*height;
}
}

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

Box d2 = new Box( ); Rectangle’s arg constructor


S.O.P(d2.findVolume()); Rectangle’s no-arg constructor
Box’s no-arg constructor
6

Rectangle r = new Rectangle(1, 2);


S.O.P(r.findPerimeter());

Box d4 = new Box(2, 4, 3);


S.O.P(d4.findArea());

Remark: S.O.P = System.out.println

49
Exercise 2: Given class Person.

public class Person {


String name = “Adam”;
String occupation = “unemployed”;

Person(){
System.out.println(“A Person is created”);
}

Person(String name){
this();
this.name = name;
}

Person(String name, String ){


this(name);
this.occupation = occupation;
}

void introduce(){
System.out.println(“My name is ”+ name +
“. I am a ” + occupation);
}

void greet(String greeting){


System.out.println(greeting);
}
}

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.

class Student _______________________________

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;

b. Identify the output when TestStudent is run.

52
Self-Review Exercises

Inheritance and constructor chaining

Consider the following classes. For short, S.O.P = System.out.println

public class Square {


int length=1;
Square(){
S.O.P("A square is generated");
}

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 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
}

double findVolume(){ return super.findArea()*height; }

public double findPerimeter(){


return 12*super.findPerimeter();
}

public int findDiagonal(){ return 1.73*length; }


}
53
Exercise 1 Identify the outputs after the following statements are executed in the class
MainTest. (Write invalid if is contains the errors)

1 public class MainTest {


2 public static void main(String[] args) {
3
4
5 Cube cub1 = new Cube(3);
6 Cube cub2 = new Cube();
7
8
9 }
10 }

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;
}

static String print(){


return "I'm a pet.";
}
}

55
public class Dog extends Pet {
String type= “dog”;
Dog(){
S.O.P("A dog is built from a no-arg constructor”);
}

Dog(String ownerName, String name, double age)


{ super(ownerName, name, age);
S.O.P("A dog is built from an arg constructor");
}
void bark() {
S.O.P(“Bok Bok”);
}
static String print(){
return "I'm a dog.";
}
}

------------------------------------------------------
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”);
}

static String print(){


return "I'm a bird.";
}

56
Exercise 4 a. Identify outputs when the following statements are executed in the
Main class.

1 public class Main {


2 public static void main(String[] args) {
3 Pet p = new Pet();
4 Dog d1 = new Dog();
5 Dog d2 = new Dog("Jack","Momo", 0.5);
6 Bird b = new Bird(“Kaew”, “Pete”, 1.0);
7
8
9
10 }
11 }

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

public class Rectangle


{ int width;
int length;
Rectangle( )
{ this(1, 2);
}
Rectangle(int width, int length)
{ this.width=width;
this.length=length;
}
int findArea() {
return width*length;
}
int findPerimeter() {
return 2*(width + length);
}
static String label(){
return "Rectangle";
}
}
-------------------------------------------------------------------------------------------------------
public class Box extends Rectangle
{ int height=3;
Box(int width, int length, int height)
{ super(width, length);
this.height=height;
}
Box()
{
}
int findVolume() {
return findArea()*height;
}
int findPerimeter() {
return 2*super.findPerimeter()+ 4*height;
}
static String label(){
return "Box";
}
}
60
1 public class TestBox
2 { public static void main(String [] args)
3 { Box b1= new Box();
4 Box b2 = new Box(1, 2, 3);
5
6 findPerimeter(b1);
7 printLabel(b2);
8
9 }
10 static void findPerimeter(Rectangle rec)
11 { S.O.P(rec.findPerimeter());
12 }
13 static void printLabel(Rectangle rec)
14 { S.O.P(rec.label());
15 }
16
17 }

61
Self-review Exercises

Polymorphism

Exercise 1 Use classes Pet, Bird, Dog to identify the outputs of TestPolymorphism

public class Pet {


String ownerName;
String name;
double age;
static String color = “white”;

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;
}

static String print(){


return "I'm a pet";
}
}

62
public class Dog extends Pet {
String type= “dog”;
Static String color = “brown”;

Dog(){

Dog(String ownerName, String name, double age)


{ super(ownerName,name,age);

}
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”);
}

static String print(){


return "I'm a bird";
}
}

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.

public class Square {


int length=1;
Square(){
S.O.P("A square is generated");
}

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
}

double findVolume(){ return super.findArea()*height; }


public double findPerimeter(){
return 12*super.findPerimeter();
}
public int findDiagonal(){ return 1.73*length; }
public static void print( ){ S.O.P("Cube”);
}
}

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.

Statement Valid or invalid


Cube cub1 = new Square();
Square sqr1= new Cube();

Exercise 2: a. Identify the outputs from line 3 of this program

1 public class MainTest {


2 public static void main(String[] args) {
3 Cube cb= new Cube();
4 printInfo(cb);
5 }
6 static printInfo(Square sq)
7 {
8 }
9 }

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

Exercise 1 Circle and label abstract methods in the class Employee.

public abstract class Employee {


String name;
String position;

public Employee(String name, String position)


{ this.name=name;
this.position = position;
printInfo();
}
protected void printInfo(){
System.out.print( name+" is a " + position);
}
abstract double getPaid();
}

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().

class PartTime extends Employee{


int numHrPerMo;
double hourlyRate;
PartTime(String name, String position,
int numHrPerMo, double hourlyRate)
{
super(name, position);
this.numHrPerMo = numHrPerMo;
this.hourlyRate = hourlyRate;
}
double getPaid(){
return numHrPerMo * hourlyRate;
}
void printInfo(){
super.printInfo();
System.out.println(“Monthly income is ” + getPaid());
}
}

69
Exercise 3: Assume that the class PartTime in Exercise 2 has been written. Identify the
output.

public class EmployeeDemo {

public static void main(String[] args){

PartTime emp = new PartTime("Jane Poke", "Cook", 20, 400.0);

System.out.println(emp.getPaid());

70
Exercise 2: Consider the interface, abstract classes, and concret classes below.

Complete headers for the following classes

public class Superman _________________________________________

public class Airplane _________________________________________

public class Bird _____________________________________________

public abstract class HomoSapien __________________________________

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.

void printDetailOfWheels() prints “4 wheels”.

void printDetailOfPowerSource() prints “4 cylinder Engine”.

It has one abstract methods: double printNumberOfSeats();

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.

Exercise 7: Identify the output after running this program

public class TestMain

public static void main(String [] ags)

{ MPV xl7 = new MPV( “Benzene”);

xl7.prinNumberOfSeats();

xl7.printDetailOfWheels();

xl7.printDetailOfPowerSource();

xl7.printTypeOfFuel();

77

You might also like