0% found this document useful (0 votes)
22 views64 pages

Revision OOP

Uploaded by

Caiting
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)
22 views64 pages

Revision OOP

Uploaded by

Caiting
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/ 64

Revision (OOP)

WIA1002/WIB1002 : Data Structure


Part 1
Check point 1
1. Name an object.
2. What can the object do?
3. Name a different object.
4. Does this 2nd object have the same
function(s) as the initially named object?

3
Class & Object
• Object : represents an entity in the real world
that can be distinctly identified (for example, a
car, apple, ball, chair, computer)
• Object has
– unique identity
– state (a set of variables/data fields/properties
with their current values)
– behaviors (a set of methods)
Class & Object
• Class
– a construct that defines objects of the same type.
– is a template, blueprint, or contract that defines
what an object’s data fields and methods will be.

• An object is an instance of a class. Can create


many objects/instances of a class.
Objects
Class Name: Circle A class template

Data Fields:
radius is _______

Methods:
getArea

Circle Object 1 Circle Object 2 Circle Object 3 Three objects of


the Circle class
Data Fields: Data Fields: Data Fields:
radius is 10 radius is 25 radius is 125

An object has both a state and behavior. The state


defines the object, and the behavior defines what
the object does.

6
UML Class Diagram
UML Class Diagram Circle Class name

radius: double Data fields

Circle() Constructors and


Circle(newRadius: double) methods
getArea(): double

circle2: Circle circle3: Circle UML notation


circle1: Circle
for objects
radius = 1.0 radius = 25 radius = 125

Question: Declare the class, properties and methods for the UML
diagram above.

7
Classes
class Circle {
/** The radius of this circle */
double radius = 1.0; Data field

/** Construct a circle object */


Circle() {
}
Constructors
/** Construct a circle object */
Circle(double newRadius) {
radius = newRadius;
}

/** Return the area of this circle */


double getArea() { Method
return radius * radius * 3.14159;
}
}
8
Constructors
Circle() {
}

Circle(double newRadius) {
radius = newRadius;
}

Constructors are a special kind of methods


that are invoked to construct objects.
9
Constructors, cont.
• Constructor
• A constructor with no parameter is referred
to as a no-arg constructor.
• must have the same name as the class itself.
• do not have a return type—not even void.
• is invoked using the new operator when an
object is created. Constructors play the role
of initializing objects.
10
Default constructor
A class may be defined without constructors. In
this case, a no-arg constructor with an empty
body is implicitly defined in the class. This
constructor, called a default constructor, is
provided automatically only if no constructors are
explicitly defined in the class.

11
Check point 2
• What is the difference between constructors
and methods?
• Can a class have more than one constructors?
• What are constructors used for? and how?
• What operator is used to invoke a
constructor?
• When will a class have a default constructor?

12
Declaring Object Reference Variables
To reference an object, assign the object to a
reference variable.

To declare a reference variable, use the syntax:

ClassName objectRefVar;

Example:
Circle myCircle;

13
Declaring/Creating Objects
in a Single Step
ClassName objectRefVar = new ClassName();

Assign object reference Create an object


Example:
Circle myCircle = new Circle();

14
Accessing Object’s Members
❑Referencing the object’s data:
objectRefVar.data
e.g., myCircle.radius

❑Invoking the object’s method:


objectRefVar.methodName(arguments)
e.g., myCircle.getArea()

15
animation
Trace Code
Declare myCircle

Circle myCircle = new Circle(5.0); no value


myCircle
Circle yourCircle = new Circle();

yourCircle.radius = 100;

16
animation
Trace Code, cont.

Circle myCircle = new Circle(5.0); no value


myCircle
Circle yourCircle = new Circle();

yourCircle.radius = 100; : Circle

radius: 5.0

Create a circle

17
animation
Trace Code, cont.

Circle myCircle = new Circle(5.0); reference value


myCircle
Circle yourCircle = new Circle();

yourCircle.radius = 100; Assign object reference : Circle


to myCircle
radius: 5.0

18
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0); reference value
myCircle
Circle yourCircle = new Circle();

yourCircle.radius = 100; : Circle

radius: 5.0

yourCircle no value

Declare yourCircle

19
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0); reference value
myCircle
Circle yourCircle = new Circle();

yourCircle.radius = 100; : Circle

radius: 5.0

yourCircle no value

: Circle
Create a new radius: 1.0
Circle object

20
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0);
myCircle reference value
Circle yourCircle = new Circle();

yourCircle.radius = 100; : Circle

radius: 5.0

yourCircle reference value

Assign object reference


to yourCircle : Circle

radius: 1.0

21
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0); reference value
myCircle
Circle yourCircle = new Circle();

yourCircle.radius = 100; : Circle

radius: 5.0

yourCircle reference value

: Circle
Change radius in radius: 100.0
yourCircle

22
Differences between Variables of
Primitive Data Types and Object Types

Created using new Circle()


Primitive type int i = 1 i 1

Object type Circle c c reference c: Circle

radius = 1

23
Copying Variables of Primitive Data
Types and Object Types
Primitive type assignment i = j

Before: After:

i 1 i 2
Object type assignment c1 = c2

j 2 j 2 Before: After:

c1 c1

c2 c2

c1: Circle C2: Circle c1: Circle C2: Circle


radius = 5 radius = 9 radius = 5 radius = 9

This object which is previously referenced by c1 is no longer referenced and


24
and is considered as garbage that will be collected automatically by JVM.
Visibility Modifiers and
Accessor/Mutator Methods
By default, the class, variable, or method can be
accessed by any class in the same package.
public
The class, data, or method is visible to any class in any
package.

private
The data or methods can be accessed only by the declaring
class.
The get and set methods are used to read and modify private
properties.
25
The private modifier restricts access to within a class, the default modifier restricts
access to within a package, and the public modifier enables unrestricted access.

26
Why Data Fields Should
Be private?

To protect data.

To make class easy to maintain.

27
Example of
Data Field Encapsulation

Circle
The - sign indicates
private modifier -radius: double The radius of this circle (default: 1.0).
-numberOfObjects: int The number of circle objects created.

+Circle() Constructs a default circle object.


+Circle(radius: double) Constructs a circle object with the specified radius.
+getRadius(): double Returns the radius of this circle.
+setRadius(radius: double): void Sets a new radius for this circle.
+getNumberOfObject(): int Returns the number of circle objects created.
+getArea(): double Returns the area of this circle.

CircleWithPrivateDataFields

TestCircleWithPrivateDataFields
28
Part 2
Class Abstraction and Encapsulation
• Class abstraction means to separate class implementation
from the use of the class. The creator of the class provides
a description of the class and let the user know how the
class can be used. The user of the class does not need to
know how the class is implemented. The detail of
implementation is encapsulated and hidden from the user
who uses the class.

Class implementation Class Contract


is like a black box (Signatures of Clients use the
hidden from the clients
Class public methods and class through the
public constants) contract of the class

30
Part 3
Inheritance
Circles, rectangles, triangles..do they share
common features?

Suppose you will define classes to model circles,


rectangles, and triangles. These classes have many
common features. What is the best way to design
these classes so to avoid redundancy?

The answer is to use inheritance.

32
Superclasses and Subclasses
GeometricObject
-color: String The color of the object (default: white).
-filled: boolean Indicates whether the object is filled with a color (default: false).
-dateCreated: java.util.Date The date when the object was created.
+GeometricObject() Creates a GeometricObject. Q:
+GeometricObject(color: String, Creates a GeometricObject with the specified color and filled 1. Is subclass a subset of
filled: boolean) values.
+getColor(): String Returns the color.
superclass?
+setColor(color: String): void Sets a new color. 2. Private accessible
+isFilled(): boolean Returns the filled property.
outside class?
+setFilled(filled: boolean): void Sets a new filled property.
+getDateCreated(): java.util.Date Returns the dateCreated. 3. Extensible?
+toString(): String Returns a string representation of this object. 4. Multiple inheritance?
5. Superclass constructor
inherited?
Circle Rectangle
-radius: double -width: double
+Circle() -height: double
+Circle(radius: double) +Rectangle()
+Circle(radius: double, color: String, +Rectangle(width: double, height: double)
filled: boolean) +Rectangle(width: double, height: double
+getRadius(): double color: String, filled: boolean)
+setRadius(radius: double): void +getWidth(): double
+getArea(): double +setWidth(width: double): void
+getPerimeter(): double +getHeight(): double
+getDiameter(): double +setHeight(height: double): void
+printCircle(): void +getArea(): double
+getPerimeter(): double
33
Calling superclass constructor
• Syntax :
super() or super(parameters)

public Circle(double radius, String color, boolean filled){


super(color, filled);
this.radius = radius;
}

34
Superclass’s Constructor Is Always Invoked
A constructor may invoke an overloaded constructor or its
superclass’s constructor. If none of them is invoked
explicitly, the compiler puts super() as the first statement
in the constructor. For example,

public A() { public A() {


is equivalent to
} super();
}

public A(double d) { public A(double d) {


// some statements is equivalent to
super();
} // some statements
}

35
• What’s the printout of running class C? In
both (a) and (b).

(a) A’s no-arg constructor is invoked (b) error – no A() constructor

36
Overriding vs. Overloading
• Overloading : define multiple methods , same
name but different parameter list; can be in
same or different classes related by
inheritance

• Overriding : provide new implementation for a


method in the subclass; different classes
related by inheritance; same method name,
same parameter list and return type

37
Overriding vs. Overloading
public class Test { public class Test {
public static void main(String[] args) { public static void main(String[] args) {
A a = new A(); A a = new A();
a.p(10); a.p(10);
a.p(10.0); a.p(10.0);
} }
} }

class B { class B {
public void p(double i) { public void p(double i) {
System.out.println(i * 2); System.out.println(i * 2);
} }
} }

class A extends B { class A extends B {


// This method overrides the method in B // This method overloads the method in B
public void p(double i) { public void p(int i) {
System.out.println(i); System.out.println(i);
} }
} }

(a) (b)
Output (a) : 10 Output (b) : a.p(10) – p(int i) - 10
a.p(10) & a.p(10.0) both a.p(10.0) – p(double i) – 20.0
38
invoke p(double i) defined in class A
Polymorphism
A variable of a supertype can refer to a subtype object. An
object of a subtype can be used wherever its supertype value
is required. This feature is known as polymorphism.

e.g 1 :
GeometricObject geoObj = new Circle();

e.g 2 :
Fruit f = new Apple();

39
Generic Programming, polymorphism, and dynamic binding
public class PolymorphismDemo { Polymorphism allows methods to be used
public static void main(String[] args) {
m(new GraduateStudent());
generically for a wide range of object
m(new Student()); arguments. This is known as generic
m(new Person()); programming. If a method’s parameter
m(new Object());
}
type is a superclass (e.g., Object), you
may pass an object to this method of any
public static void m(Object x) { of the parameter’s subclasses (e.g.,
System.out.println(x.toString());
}
Student or String). When an object (e.g.,
} a Student object or a String object) is
used in the method, the particular
class GraduateStudent extends Student {
}
implementation of the method of the
object that is invoked (e.g., toString) is
class Student extends Person { determined dynamically by the Java
public String toString() {
return "Student";
Virtual Machine at runtime. This
} capability is known as dynamic binding.
}

class Person extends Object {


Output :
public String toString() { Student
return "Person";
}
Student
} Person
Java.lang.Object@39274

40
Visibility/Accessibility Modifiers
Summary

Modifier Accessed Accessed Accessed Accessed


on members from the from the from a from a different
in a class same class same package subclass package

public

protected -

default - -

private - - -

41
Visibility Modifiers
package p1;
public class C1 { public class C2 {
public int x; C1 o = new C1();
protected int y; can access o.x;
int z; can access o.y;
private int u; can access o.z;
cannot access o.u;
protected void m() {
} can invoke o.m();
} }

package p2;

public class C3 public class C4 public class C5 {


extends C1 { extends C1 { C1 o = new C1();
can access x; can access x; can access o.x;
can access y; can access y; cannot access o.y;
can access z; cannot access z; cannot access o.z;
cannot access u; cannot access u; cannot access o.u;
can invoke m(); can invoke m(); cannot invoke o.m();
} } }

42
Part 4
Abstract Classes and Abstract Methods
GeometricObject Abstract class

-color: String
-filled: boolean
-dateCreated: java.util.Date
GeometricObject
The # sign indicates
protected modifie r #Geo metric Object()
#Geo metric Object(color: string,
filled: boolean) Circle
+getColor(): St ring
+setColor(colo r: String): void
+isFilled(): boolean
+setFilled(filled : boolean): void
Rectangle
+getDateCreated(): java.util.Date
+toString(): String
+getArea(): double
Abstract methods +getPerimeter(): double
Methods getArea and getPerimeter a re overridden in
are ita lic ized
Circ le and Rectangle. Superclass methods are generally
omitted in the UM L d iagra m for subclasses .

Circle Rectangle
-radius: double -width: double

TestGeometricObject
-height: double
+Circle ()
+Circle (radius: double) +Rectangle()

+Circle (radius: double, color: string, +Rectangle(width: double, height: double)


filled: boolean) +Rectangle(width: double, height: double,
+getRadius(): double color: string, filled: boolean)

+setRadius(radius: double): void +getWidth(): double

+getDia meter(): double +setWidth(width: double): void


+getHeight(): double
+setHeight(height: double): void

44
1. abstract method in abstract class
An abstract method cannot be contained in a
nonabstract class.
public class GeometricObject {
public abstract double getArea();
}

If a subclass of an abstract superclass does not


implement all the abstract methods, the subclass must
be defined abstract.

45
2. object cannot be created from
abstract class
An abstract class cannot be instantiated
using the new operator
GeometricObject geoObj = new GeometricObject();

but you can still define its constructors,


which are invoked in the constructors of its
subclasses. For instance, the constructors of
GeometricObject are invoked in the Circle
class and the Rectangle class.
46
3. abstract class without abstract
method
A class that contains abstract methods must
be abstract.
public abstract class GeometricObject {
public abstract double getArea();
}

However, it is possible to define an abstract class that


contains no abstract methods. In this case, you cannot
create instances of the class using the new operator.
This class is used as a base class for defining a new
subclass.
47
4. superclass of abstract class may be
concrete

A subclass can be abstract even if its


superclass is concrete. For example, the
Object class is concrete, but its subclasses,
such as GeometricObject, may be abstract.
public class Object {}
public abstract class GeometricObject {}

48
5. concrete method overridden to be
abstract
A subclass can override a method from its
superclass to define it abstract. This is rare,
but useful when the implementation of the
method in the superclass becomes invalid in
the subclass. In this case, the subclass must
be defined abstract.

49
public abstract class GeometricObject{
public String someMethod();
}
public abstract class Circle extends
GeometricObject {
public abstract String someMethod();
}
6. abstract class as type

You cannot create an instance/object from an


abstract class using the new operator, but an
abstract class can be used as a data type.
Therefore, the following statement, which
creates an array whose elements are of
GeometricObject type, is correct.
GeometricObject[] geo = new GeometricObject[10];
geo[0] = new Circle();
geo[1] = new Rectangle();
51
What is an interface?
Why is an interface useful?
• A classlike construct that contains only constants
and abstract methods.
• Similar to an abstract class, but the intent of an
interface is to specify common behavior for
objects. For example, you can specify that the
objects are comparable, edible, cloneable using
appropriate interfaces.
• Cannot create an instance using the new operator

52
Define an Interface
To distinguish an interface from a class, Java uses the
following syntax to define an interface:
public interface InterfaceName {
constant declarations;
method signatures;
}

Example:
public interface Edible {
/** Describe how to eat */
public abstract String howToEat();
}

53
Example
You can now use the Edible interface to specify whether an object
is edible. This is accomplished by letting the class for the object
implement this interface using the implements keyword. For
example, the classes Chicken and Fruit implement the Edible
interface (See TestEdible).

Edible TestEdible Run

54
Question: What is the output?
• Java allows only single inheritance for class
extension but allows multiple extensions for
interfaces.

public class NewClass extends BaseClass


implements Interface1, ...., InterfaceN {
}
• An interface can inherit other interfaces using
extends keyword. The extended interface is
called subinterface.

public interface NewInterface extends


Interface1, ...., InterfaceN {
//constants and abstract methods
}
Extend vs Implement
A Java class may extend one class and
implement multiple interfaces.
An interface may extend any number of
interfaces; however an interface may not
implement an interface.

A class that implements an interface must


implement all of the methods described in
the interface, or be an abstract class.
Omitting Modifiers in Interfaces
All data fields are public static final and all methods are public
abstract in an interface. For this reason, these modifiers can be
omitted, as shown below:

public interface T1 { public interface T1 {


public static final int K = 1; Equivalent int K = 1;

public abstract void p(); void p();


} }

A constant defined in an interface can be accessed using syntax


InterfaceName.CONSTANT_NAME (e.g., T1.K).

59 59
Interfaces vs. Abstract Classes
In an interface, the data must be constants; an abstract class can
have all types of data.
Each method in an interface has only a signature without
implementation; an abstract class can have concrete methods.

Variables Constructors Methods

Abstract No restrictions Constructors are invoked by subclasses No restrictions.


class through constructor chaining. An abstract
class cannot be instantiated using the
new operator.

Interface All variables No constructors. An interface cannot be All methods must be


must be public instantiated using the new operator. public abstract
static final instance methods

60
Abstract class Interface
Check point 3
1. How to do you create an interface called
Walking having a howToWalk()?
2. If A is an abstract class. Can you create an
instance using new A() ?
3. If A is an abstract class. Can you declare a
reference variable x with type A like this?
A x;
• Which is a correct interface?

Correct answer : (d)


References
• Part 1: Chapter 9 Objects and Classes, Liang,
Introduction to Java Programming, 10th Edition, Global
Edition, Pearson, 2015
• Part 2: Chapter 10 Thinking in Objects, Liang,
Introduction to Java Programming, 10th Edition, Global
Edition, Pearson, 2015
• Part 3: Chapter 11 Inheritance and Polymorphism,
Liang, Introduction to Java Programming, 10th Edition,
Global Edition, Pearson, 2015
• Part 4: Chapter 13 Abstract Classes and Interfaces,
Liang, Introduction to Java Programming, 10th Edition,
Global Edition, Pearson, 2015

You might also like