0% found this document useful (0 votes)
12 views45 pages

05 OOP Interface

The document outlines key concepts of Object-Oriented Programming (OOP) in Java, focusing on the Object class, the equals method, and polymorphism. It explains how to properly implement the equals method for custom classes, the use of type casting, and the role of interfaces in defining common behaviors across different classes. Additionally, it discusses the principles of polymorphism, allowing methods to operate on objects of different types seamlessly.

Uploaded by

tam.le2302220
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)
12 views45 pages

05 OOP Interface

The document outlines key concepts of Object-Oriented Programming (OOP) in Java, focusing on the Object class, the equals method, and polymorphism. It explains how to properly implement the equals method for custom classes, the use of type casting, and the role of interfaces in defining common behaviors across different classes. Additionally, it discusses the principles of polymorphism, allowing methods to operate on objects of different types seamlessly.

Uploaded by

tam.le2302220
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/ 45

CS206V: Object Oriented

Programming
(Spring 2024)
Dr. Cao Tien Dung
School of Information Technology – Tan Tao University
Class Object
• All types of objects have a superclass
named Object.
• Every class implicitly extends Object
• The Object class defines several methods:
• public String toString()
Returns a text representation of the object,
often so that it can be printed.
• public boolean equals(Object other)
Compare the object to any other for equality.
Returns true if the objects have equal state.

Spring'2024 Cao Tien Dung, PhD. 2


Object variables
• You can store any object in a variable of type Object.
Object o1 = new Point(5, -3);
Object o2 = "hello there";
Object o3 = new Scanner(System.in);
• An Object variable only knows how to do general things.
String s = o1.toString(); // ok
int len = o2.length(); // error
String line = o3.nextLine(); // error
• You can write methods that accept an Object parameter.
public void checkForNull(Object o) {
if (o == null) {
throw new IllegalArgumentException();
}
}

Spring'2024 Cao Tien Dung, PhD. 3


Recall: comparing objects
• The == operator does not work well with objects.
== compares references to objects, not their state.
It only produces true when you compare an object to
itself.
Point p1 = new Point(5, 3);
Point p2 = new Point(5, 3);
if (p1 == p2) { // false
System.out.println("equal"); x 5 y 3
p1
} ...

p2 x 5 y 3
...

Spring'2024 Cao Tien Dung, PhD. 4


The equals method
• The equals method compares the state of objects.
if (str1.equals(str2)) {
System.out.println("the strings are equal");
}

• But if you write a class, its equals method behaves like ==


if (p1.equals(p2)) { // false :-(
System.out.println("equal");
}

• This is the behavior we inherit from class Object.


• Java doesn't understand how to compare Points by default.

Spring'2024 Cao Tien Dung, PhD. 5


Flawed equals method
• We can change this behavior by writing an equals method.
• Ours will override the default behavior from class Object.
• The method should compare the state of the two objects and return
true if they have the same x/y position.

• A flawed implementation:
public boolean equals(Point other) {
if (x == other.x && y == other.y) {
return true;
} else {
return false;
}
}

Spring'2024 Cao Tien Dung, PhD. 6


Flaws in our method
• The body can be shortened to the following:
// boolean zen
return x == other.x && y == other.y;

• It should be legal to compare a Point to any object


(not just other Points):
// this should be allowed
Point p = new Point(7, 2);
if (p.equals("hello")) { // false
...

• equals should always return false if a non-Point is passed.

Spring'2024 Cao Tien Dung, PhD. 7


equals and Object
public boolean equals(Object name) {
statement(s) that return a boolean value ;
}

• The parameter to equals must be of type Object.


• Object is a general type that can match any object.
• Having an Object parameter means any object can be
passed.
• If we don't know what type it is, how can we compare it?

Spring'2024 Cao Tien Dung, PhD. 8


Another flawed version
• Another flawed equals implementation:
public boolean equals(Object o) {
return x == o.x && y == o.y;
}
• It does not compile:
Point.java:36: cannot find symbol
symbol : variable x
location: class java.lang.Object
return x == o.x && y == o.y;
^
• The compiler is saying,
"o could be any object. Not every object has an x
field."
Spring'2024 Cao Tien Dung, PhD. 9
Type-casting objects
• Solution: Type-cast the object parameter to a
Point.
public boolean equals(Object o) {
Point other = (Point) o;
return x == other.x && y == other.y;
}

• Casting objects is different than casting


primitives.
• Really casting an Object reference into a Point reference.
• Doesn't actually change the object that was passed.
• Tells the compiler to assume that o refers to a Point
object.

Spring'2024 Cao Tien Dung, PhD. 10


Casting objects diagram
• Client code:
Point p1 = new Point(5, 3);
Point p2 = new Point(5, 3);
if (p1.equals(p2)) {
System.out.println("equal");
}
x 5 y 3 o
other
public boolean equals(Object o) {
Point other = (Point) o;
return x == other.x && y == other.y;
p1 }

p2 x 5 y 3
...
Spring'2024 Cao Tien Dung, PhD. 11
Comparing different types
Point p = new Point(7, 2);
if (p.equals("hello")) { // should be false
...
}
• Currently our method crashes on the above code:
Exception in thread "main"
java.lang.ClassCastException: java.lang.String
at Point.equals(Point.java:25)
at PointMain.main(PointMain.java:25)
• The culprit is the line with the type-cast:
public boolean equals(Object o) {
Point other = (Point) o;
Spring'2024 Cao Tien Dung, PhD. 12
The instanceof keyword
if (variable instanceof type) {
statement(s); expression result
} s instanceof Point false
s instanceof String true
p instanceof Point true
• Asks if a variable refers p instanceof String false
to an object of a given type. p instanceof Object true
• Used as a boolean test. s instanceof Object true
null instanceof false
String s = "hello"; String
Point p = new Point(); null instanceof false
Object

Spring'2024 Cao Tien Dung, PhD. 13


Final equals method
// Returns whether o refers to a Point object with
// the same (x, y) coordinates as this Point.
public boolean equals(Object o) {
if (o instanceof Point) {
// o is a Point; cast and compare it
Point other = (Point) o;
return x == other.x && y == other.y;
} else {
// o is not a Point; cannot be equal
return false;
}
}

Spring'2024 Cao Tien Dung, PhD. 14


Polymorphism
Polymorphism
• Polymorphism: Ability for the same code to be
used with different types of objects and behave
differently with each.

• System.out.println can print any type of object.


• Each one displays in its own way on the console.

System.out.println(“Hello”); // Hello
System.out.println(10); // 10
System.out.println(‘c’); // c

Spring'2024 Cao Tien Dung, PhD. 16


Coding with polymorphism
• Can a variable of class T hold an object of any
subclass of T? YES
Employee em = new Marketer();
• you can call any methods of the Employee class on em
• When a method is called on em, it behaves as a
Marketer.
System.out.println(em.getSalary()); // 45000 marketer

• It is possible to call em.advertise(“Dove”)?


(later)

Spring'2024 Cao Tien Dung, PhD. 17


Polymorphism and parameters
• You can pass any subtype of a parameter's type.
public class EmployeeMain {
public static void main(String[] args) {
Lawyer lisa = new Lawyer(); OUTPUT:
Secretary steve = new Secretary(); salary: 50000.0
v.days: 12
printInfo(lisa); v.form: pink
printInfo(steve); salary: 40000.0
} v.days: 12
v.form: yellow
public static void printInfo(Employee empl) {
System.out.println("salary: " + empl.getSalary());
System.out.println("v.days: " + empl.getVacationDays());
System.out.println("v.form: " + empl.getVacationForm());
System.out.println();
}
}

Spring'2024 Cao Tien Dung, PhD. 18


Polymorphism and arrays
• Arrays of superclass types can store any subtype as elements.
public class EmployeeMain2 {
public static void main(String[] args) {
Employee[] e = { new Lawyer(), new Secretary(),
new Marketer(), new LegalSecretary() };
for (int i = 0; i < e.length; i++) {
System.out.println("salary: " + e[i].getSalary());
System.out.println();
}
}
}
Output:
salary: 50000 //lawyer
salary: 40000
salary: 45000 //marketer
salary: 40000
Spring'2024 Cao Tien Dung, PhD. 19
A polymorphism problem
• Suppose that the following four classes have been declared:
public class Foo {
public void method1() {
System.out.println("foo 1");
}
public void method2() {
System.out.println("foo 2");
}
public String toString() {
return "foo";
}
}
public class Bar extends Foo {
public void method2() {
System.out.println("bar 2");
}
}

Spring'2024 Cao Tien Dung, PhD. 20


A polymorphism problem
public class Baz extends Foo {
public void method1() {
System.out.println("baz 1");
}
public String toString() {
return "baz";
}
}
public class Mumble extends Baz {
public void method2() {
System.out.println("mumble 2");
}
}

• What would be the output of the following client code?


Foo[] pity = {new Baz(), new Bar(), new Mumble(), new Foo()};
for (int i = 0; i < pity.length; i++) {
System.out.println(pity[i]);
pity[i].method1();
pity[i].method2();
System.out.println();
}

Spring'2024 Cao Tien Dung, PhD. 21


Diagramming the classes
• Add classes from top (superclass) to bottom
(subclass).
• Include all inherited methods.

Spring'2024 Cao Tien Dung, PhD. 22


Finding output with tables

method Foo Bar Baz Mumble

method1 foo 1 foo 1 baz 1 baz 1

method2 foo 2 bar 2 foo 2 mumble 2

toString foo foo baz baz

Spring'2024 Cao Tien Dung, PhD. 23


Polymorphism answer
Foo[] pity = {new Baz(), new Bar(), new Output:
baz
Mumble(), new Foo()}; baz 1
foo 2
for (int i = 0; i < pity.length; i++) { foo
foo 1
System.out.println(pity[i]); bar 2
baz
pity[i].method1(); baz 1
mumble 2
pity[i].method2(); foo
foo 1
foo 2
System.out.println();
}

Spring'2024 Cao Tien Dung, PhD. 24


Casting references
• A variable can only call that type's methods, not a
subtype's.
Employee ed = new Lawyer();
int hours = ed.getWorkHours(); //ok;it's in Employee
ed.sue(); // compiler error

• The compiler's reasoning is, variable ed could store


any kind of employee, and not all kinds know how to sue
• To use Lawyer methods on ed, we can type-cast it.
Lawyer theRealEd = (Lawyer) ed;
theRealEd.sue(); // ok
((Lawyer) ed).sue(); // shorter version

Spring'2024 Cao Tien Dung, PhD. 25


More about casting
• The code crashes if you cast an object too far down the tree.
Employee eric = new Secretary();
((Secretary) eric).takeDictation("hi"); // ok
((LegalSecretary) eric).fileLegalBriefs(); // exception
//(Secretary object doesn't know how to file briefs)

• You can cast only up and down the tree, not


sideways.
Lawyer linda = new Lawyer();
((Secretary) linda).takeDictation("hi"); // error

• Casting doesn't actually change the object's


behavior.
It just gets the code to compile/run.
((Employee) linda).getVacationForm() // pink (Lawyer's)

Spring'2024 Cao Tien Dung, PhD. 26


Interface
Relatedness of types
• Write a set of Circle, Rectangle, and Triangle
classes.

• Certain operations that are common to all


shapes.
• perimeter: distance around the outside of the shape
• area: amount of 2D space occupied by the shape

• Every shape has them but computes them


differently.

Spring'2024 Cao Tien Dung, PhD. 28


Shape area, perimeter
• Rectangle (as defined by width w and height h):
• area = w * h
• perimeter = 2w + 2h

• Circle (as defined by radius r):


• area = p * r2
• perimeter = 2 * p * r

• Triangle (as defined by side lengths a, b, and c)


• area = √(s (s - a) (s - b) (s - c))
where s = ½ (a + b + c)
• perimeter = a + b + c

Spring'2024 Cao Tien Dung, PhD. 29


Common behavior
• Write shape classes with methods perimeter and area.

• We'd like to be able to write client code that


treats different kinds of shape objects in the same
way, such as:
• Write a method that prints any shape's area and perimeter.
• Create an array of shapes that could hold a mixture of the
various shape objects.
• Write a method that could return a rectangle, a circle, a
triangle, or any other shape we've written.
• Make a DrawingPanel display many shapes on screen.

Spring'2024 Cao Tien Dung, PhD. 30


Interfaces
• interface: A list of methods that a class can
implement.
• Inheritance gives you an is-a relationship and code-
sharing.
• A Lawyer object can be treated as an Employee, and
Lawyer inherits Employee's code.
• Interfaces give you an is-a relationship without code
sharing.
• A Rectangle object can be treated as a Shape.
• Analogous to the idea of roles or certifications:
• "I'm certified as a Certified Public Accountant. That means I
know how to compute taxes, perform audits, and do consulting."
• "I'm certified as a Shape. That means I know how
to compute my area and perimeter."

Spring'2024 Cao Tien Dung, PhD. 31


Declaring an interface
public interface name {
public type name(type name, ..., type name);
public type name(type name, ..., type name);
...
}
Example:
public interface Vehicle {
public double speed();
public void setDirection(int direction);
}

• abstract method: A header without an implementation.


• The actual body is not specified, to allow/force different classes to
implement the behavior in its own way.

Spring'2024 Cao Tien Dung, PhD. 32


Shape interface

public interface Shape {


public double area();
public double perimeter();
}

• This interface describes the features common to all


shapes.
(Every shape has an area and perimeter.)

Spring'2024 Cao Tien Dung, PhD. 33


Implementing an interface
public class name implements interface {
...
}
• Example:
public class Bicycle implements Vehicle {
...
}

• A class can declare that it implements an interface.


• This means the class must contain each of the abstract methods in
that interface. (Otherwise, it will not compile.)

(What must be true about the Bicycle class for it to compile?)

Spring'2024 Cao Tien Dung, PhD. 34


Interface requirements
• If a class claims to be a Shape but doesn't
implement the area and perimeter methods, it will
not compile.
• Example:
public class Banana implements Shape {
...
}

• The compiler error message:


Banana.java:1: Banana is not abstract and does not override
abstract method area() in Shape
public class Banana implements Shape {
^

Spring'2024 Cao Tien Dung, PhD. 35


Complete Circle class
// Represents circles.
public class Circle implements Shape {
private double radius;

// Constructs a new circle with the given radius.


public Circle(double radius) {
this.radius = radius;
}

// Returns the area of this circle.


public double area() {
return Math.PI * radius * radius;
}

// Returns the perimeter of this circle.


public double perimeter() {
return 2.0 * Math.PI * radius;
}
}

Spring'2024 Cao Tien Dung, PhD. 36


Complete Rectangle class
// Represents rectangles.
public class Rectangle implements Shape {
private double width;
private double height;

// Constructs a new rectangle with the given dimensions.


public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}

// Returns the area of this rectangle.


public double area() {
return width * height;
}

// Returns the perimeter of this rectangle.


public double perimeter() {
return 2.0 * (width + height);
}
}

Spring'2024 Cao Tien Dung, PhD. 37


Complete Triangle class
// Represents triangles.
public class Triangle implements Shape {
private double a;
private double b;
private double c;

// Constructs a new Triangle given side lengths.


public Triangle(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}

// Returns this triangle's area using Heron's formula.


public double area() {
double s = (a + b + c) / 2.0;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}

// Returns the perimeter of this triangle.


public double perimeter() {
return a + b + c;
}
}

Spring'2024 Cao Tien Dung, PhD. 38


Interfaces + polymorphism
• Interfaces don't benefit the class so much as the client.
• Interface's is-a relationship lets the client use polymorphism.

public static void printInfo(Shape s) {


System.out.println("The shape: " + s);
System.out.println("area : " + s.area());
System.out.println("perim: " + s.perimeter());
}

• Any object that implements the interface may be passed.


Circle circ = new Circle(12.0);
Rectangle rect = new Rectangle(4, 7);
Triangle tri = new Triangle(5, 12, 13);
printInfo(circ);
printInfo(tri);
printInfo(rect);

Shape[] shapes = {tri, circ, rect};

Spring'2024 Cao Tien Dung, PhD. 39


Interface diagram

• Arrow goes up from class to interface(s) it implements.


• There is a supertype-subtype relationship here;
e.g., all Circles are Shapes, but not all Shapes are Circles.
• This kind of picture is also called a UML class diagram.

Spring'2024 Cao Tien Dung, PhD. 40


Abstract class
recall: interface
• Interface: a list of methods that an object can
implement.
• all methods are abstract methods (only declare, not
implement).
• each method is implemented by different ways for each
specified object.
• Problem:
• some of these methods have the same implementation way? It means
some codes can share between objects.
• Inheritance: most of methods have different way to implement
(sharing code is not useful).
• Interface: can’t implement some common states (fields) and
behaviors (methods).

Spring'2024 Cao Tien Dung, PhD. 42


Abstract class
• Abstract class = inheritance (sharing common code) + interface (abstract
methods that can’t share code).
• a class that is declared abstract: it may or may not include abstract method.
• abstract methods: a methods that is declared without implementation.
public abstract <type> <method name>(parameter);

• If a class contains at least one abstract method, the class itself must be
declared abstract.

public abstract class <name> {


// declare fields
// declare non-abstract methods
public abstract <type> <name>();
}

Spring'2024 Cao Tien Dung, PhD. 43


Abstract class (cont.)
• An attempt to create an instance from an abstract
class will produce a compiler error.
public abstract class GraphicObject{
private int x, y;
public void moveTo(int newX, int newY){ // implement}
public abstract void draw();
public abstract void resize();
}

public class Rectangle extends GraphicObject {


//implement two abstract method here
}

• client side
GraphicObject g = new GraphicObject();//Compile error
Rectangle rect = new Rectangle(); //OK

Spring'2024 Cao Tien Dung, PhD. 44


Abstract classes vs interfaces
• Abstract class can contain fields that are not static or final, and
contain the implemented methods.
• Abstract classes are similar interfaces, except that provide a
partial implementation and leaving the rest to its subclass to
complete the implementation.
• A class that implements an interface, it must implement all methods
of interface. How we can implement some of them?
• solution is abstract class: Y is an interface.
public abstract class X implements Y{
// implement some methods of Y and additional
}
public class XX extends X{
// implement remaining methods of Y
}

Spring'2024 Cao Tien Dung, PhD. 45

You might also like