Revision OOP
Revision OOP
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.
Data Fields:
radius is _______
Methods:
getArea
6
UML Class Diagram
UML Class Diagram Circle Class name
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
Circle(double newRadius) {
radius = newRadius;
}
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.
ClassName objectRefVar;
Example:
Circle myCircle;
13
Declaring/Creating Objects
in a Single Step
ClassName objectRefVar = new ClassName();
14
Accessing Object’s Members
❑Referencing the object’s data:
objectRefVar.data
e.g., myCircle.radius
15
animation
Trace Code
Declare myCircle
yourCircle.radius = 100;
16
animation
Trace Code, cont.
radius: 5.0
Create a circle
17
animation
Trace Code, cont.
18
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0); reference value
myCircle
Circle yourCircle = new 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();
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();
radius: 5.0
radius: 1.0
21
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0); reference value
myCircle
Circle yourCircle = new Circle();
radius: 5.0
: Circle
Change radius in radius: 100.0
yourCircle
22
Differences between Variables of
Primitive Data Types and Object Types
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
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.
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.
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.
30
Part 3
Inheritance
Circles, rectangles, triangles..do they share
common features?
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)
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,
35
• What’s the printout of running class C? In
both (a) and (b).
36
Overriding vs. Overloading
• Overloading : define multiple methods , same
name but different parameter list; can be in
same or different classes related by
inheritance
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);
} }
} }
(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.
}
40
Visibility/Accessibility Modifiers
Summary
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;
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()
44
1. abstract method in abstract class
An abstract method cannot be contained in a
nonabstract class.
public class GeometricObject {
public abstract double getArea();
}
45
2. object cannot be created from
abstract class
An abstract class cannot be instantiated
using the new operator
GeometricObject geoObj = new 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
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).
54
Question: What is the output?
• Java allows only single inheritance for class
extension but allows multiple extensions for
interfaces.
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.
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?