05 OOP Interface
05 OOP Interface
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.
p2 x 5 y 3
...
• A flawed implementation:
public boolean equals(Point other) {
if (x == other.x && y == other.y) {
return true;
} else {
return false;
}
}
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
System.out.println(“Hello”); // Hello
System.out.println(10); // 10
System.out.println(‘c’); // c
• If a class contains at least one abstract method, the class itself must be
declared abstract.
• client side
GraphicObject g = new GraphicObject();//Compile error
Rectangle rect = new Rectangle(); //OK