Anda di halaman 1dari 19

@NGUYỄN Thị Thu Trang, trangntt@soict.hust.edu.

vn 2

Outline

1. Redefine/Overiding
OBJECT-ORIENTED LANGUAGE AND THEORY
2. Abstract class
7. ABSTRACT CLASS AND INTERFACE
3. Single inheritance and multi-inheritance
Nguyen Thi Thu Trang
trangntt@soict.hust.edu.vn
4. Interface

3 4

Outline 1. Re-definition or Overriding


• A child
class can define a method with the same
1. Redefine/Overiding name of a method in its parent class:
2. Abstract class • If the new method has the same name but different
signature (number or data types of method’s
3. Single inheritance and multi-inheritance arguments)
à Method Overloading
4. Interface
• If the new method has the same name and signature
à Re-definition or Overriding
(Method Redefine/Override)

1
5 6
class Shape {
1. Re-definition or Overriding (2) protected String name;
Shape(String n) { name = n; }
public String getName() { return name; }
• Overriding method will replace or add more details to the
public float calculateArea() { return 0.0f; }
overriden method in the parent class }
• Objects of child class will use the re-defined method class Circle extends Shape {
private int radius;
Circle(String n, int r){
super(n);
radius = r;
}

public float calculateArea() {


float area = (float) (3.14 * radius * radius);
return area;
}
}

7 8

class Square extends Shape {


private int side;
Class Triangle
Square(String n, int s) { class Triangle extends Shape {
super(n);
private int base, height;
side = s; Triangle(String n, int b, int h) {
} super(n);
public float calculateArea() {
base = b; height = h;
float area = (float) side * side; }
return area; public float calculateArea() {
}
float area = 0.5f * base * height;
} return area;
}
}

2
9 10

package abc;
this and super public class Person {
protected String name;
• this and super can use non-static protected int age;
methods/attributes and constructors public String getDetail() {
String s = name + "," + age;
• this: searching for methods/attributes in the
return s;
current class }
• super: searching for methods/attributes in the }
direct parent class
import abc.Person;
• Keyword super allows re-using the source-code public class Employee extends Person {
of a parent class in its child classes double salary;
public String getDetail() {
String s = super.getDetail() + "," + salary;
return s;
}
}

11 12

Overriding Rules Overriding Rules (2)


• Overriding methods must have: • Accessibilitycan not be more restricted in a
• An argument list that is the same as the overriden child class (compared to in its parent class)
method in the parent class • For example, if overriding a protected method, the
• The same return data types as the overriden method new overriding method can only be protected or
in the parent class public, and can not be private.
• Can not override:
• Constant (final) methods in the parent class
• Static methods in the parent class
• Private methods in the parent class

3
13 14

Example Example: private


class Parent { class Parent {
public void doSomething() {} public void doSomething() {}
protected int doSomething2() { private int doSomething2() {
return 0; cannot override: attempting to use return 0;
} incompatible return type }
} }
class Child extends Parent { class Child extends Parent {
protected void doSomething() {} public void doSomething() {}
protected void doSomething2() {} private void doSomething2() {}
} }

cannot override: attempting to assign


weaker access privileges; was public

package university;
public class Faculty extends Person {
Person, Student và Faculty private int hireYear; Class Faculty
public Faculty( ) { super( ); hireYear = -1; }
public Faculty( String n, String id, int yr ) {
super(n, id);
hireYear = yr;
}
public Faculty( Faculty f ) {
this( f.getName( ), f.getIdNum( ), f.hireYear );
}
int getHireYear( ) { return hireYear; }
void setHireYear( int yr ) { hireYear = yr; }
public String toString( ) {
return super.toString( ) + " " + hireYear;
}
public boolean equals( Faculty f ) {
return super.equals( f ) && hireYear == f.hireYear;
}
}

4
Overriding Re-definition with final
• When a derived class wants to change a function inherited • Sometimes we want to restrict the re-definition because
from its parent class (super). of:
• Correctness: The re-definition of a method in a derived class
public class Person {

can lead the method to a wrong behavior
public String toString( ) { … } • Efficiency: The dynamic linking mechanism is not efficient in
} time as the static linking mechanism. If a method should not
public class Student extends Person {
Re-define the method of be re-defined in derrived classes, we shold use the keyword

the parent class final with the method
public String toString( ) { … }
}
Student bob = new Student("Bob Goodstudent","123-45-
6789",2004,4.0 ); public final String baseName () {
System.out.println( "Bob's info: " + bob.toString( ) ); return “Person”;}
}
Calling to the method of the child
class

Basic class ship


public class Ship { Basic class ship
public double x=0.0, y=0.0, speed=1.0, direction=0.0;
public String name; public void move() {
public Ship(double x, double y, double speed, double move(1);
direction, String name) {
}
this.x = x;
public void move(int steps) {
this.y = y;
this.speed = speed; double angle = degreesToRadians(direction);
x = x + (double)steps * speed * Math.cos(angle);
this.direction = direction;
y = y + (double)steps * speed * Math.sin(angle);
this.name = name;
} }
public Ship(String name) { public void printLocation() {
System.out.println(name + " is at ("+ x + "," + y +
this.name = name; ").");
} }
private double degreesToRadians(double degrees) {
}
return(degrees * Math.PI / 180.0); ...
}
...

5
Derived class Speedboat Class Book2
public class Speedboat extends Ship {
private String color = "red"; class Book2 {
public Speedboat(String name) { protected int pages;
super(name);
setSpeed(20); public Book2(int pages) {
} this.pages = pages;
public Speedboat(double x, double y, double speed, }
double direction, String name, String color) {
super(x, y, speed, direction, name); public void pageMessage() {
setColor(color); System.out.println("Number of pages: " +
} pages);
public void printLocation() { }
System.out.print(getColor().toUpperCase() + " "); }
super.printLocation();
}
...

Class Dictionary2 Class Words2


class Dictionary2 extends Book2 { class Words2 {
private int definitions; public static void main (String[] args) {
Dictionary2 webster = new Dictionary2(1500, 52500);
public Dictionary2(int pages, int definitions) { webster.pageMessage();
super (pages); webster.definitionMessage();
this.definitions = definitions; }
} }

public void definitionMessage () {


System.out.println("Number of definitions: " + Results:
definitions); C:\Examples>java Words2
System.out.println("Definitions per page: " + Number of pages: 1500
definitions/pages); Number of definitions: 52500
} Definitions per page: 35
}

6
Class Book3 Class: Dictionary3a
class Book3 { class Dictionary3a extends Book3 {
protected String title; private int definitions;
protected int pages;
public Dictionary3a(String title, int pages,
public Book3(String title, int pages) { int definitions) {
this.title = title; super (title, pages);
this.pages = pages; this.definitions = definitions;
} }

public void info() { public void info() {


System.out.println("Title: " + title); System.out.println("Dictionary: " + title);
System.out.println("Number of pages: " + pages); System.out.println("Number of definitions: " +
} definitions);
} System.out.println("Definitions per page: " +
definitions/pages);
}
}

Class: Dictionary3b Class Books


class Dictionary3b extends Book3 { class Books {
private int definitions; public static void main (String[] args) {
Book3 java = new Book3("Introduction to Java", 350);
public Dictionary3b(String title, int pages, java.info();
int definitions) { System.out.println();
super (title, pages); Dictionary3a webster1 =
this.definitions = definitions; new Dictionary3a("Webster English Dictionary",
} 1500, 52500);
webster1.info();
public void info() { System.out.println();
super.info(); Dictionary3b webster2 =
System.out.println("Number of definitions: " + new Dictionary3b("Webster English Dictionary",
definitions); 1500, 52500);
System.out.println("Definitions per page: " + webster2.info();
definitions/pages); }
} }
}

7
Class: Books Examples: Point, Circle, Cylinder

Kết quả:
C:\Examples>java Books
Title: Introduction to Java
Number of pages: 350

Dictionary: Webster English Dictionary


Number of definitions: 52500
Definitions per page: 35

Title: Webster English Dictionary


Number of pages: 1500
Number of definitions: 52500
Definitions per page: 35

Ví dụ: Point, Circle, Cylinder Re-definition: Cylinder


• Cylinder must re-define
getArea() inherited from Circle
• Use getArea() and
getCircumference() of the
parent class

8
Problems in Inheritance
• Casting an object of a parent class to an
object of its derived class is called Instrument
upcasting

• All messages sent to objects of a basic class


can be sent to objects of its derived classes. Wind

Upcasting – Java Upcast


import java.util.*; // Wind objects are instruments
// because they have the same class Car{};
class Instrument { // interface:
public void play() {} class ElectricCar extends Car{};
class Wind extends Instrument {
static void tune(Instrument i) { Car c = new ElectricCar ();
public static void main(String[] args) {
// ...
i.play();
Wind flute = new Wind();
} Instrument.tune(flute); // Upcasting
} } • Reference type and object type are two
} different concepts
Instrument • Objects referred by c are in type
ElectricCar

Wind

9
Upcast Down Cast
• Car c = new Car(); • When assigning an object of a more basic type to a
• ElectricCar ec = new ElectricCar (); derived type.
• c = ec; • Be careful in usage
• Do it explicitly
• Automatic upcast (implicit)
Car c = new ElectricCar(); // Up-casting not
• Types of objects do not be changed
explicitly
c.recharge(); // Error
// Down-casting explicitly
ElectricCar ec = (ElectricCar)c;
ec.recharge(); // ok

Down Cast Avoiding Down Cast Error


• Using instanceof operation
Car c = new Car();
c.recharge(); // lỗi Runtime Error Car c = new Car();
// explicit downcast
ElectricCar ec;
ElectricCar ec = (ElectricCar)c;
ec.recharge(); // lỗi
if (c instanceof ElectricCar ){
ec = (ElectricCar) c;
ec.recharge();
}

((ElectricCar)c).recharge();

10
41

Outline Abstract Class


• An abstract class is a class that we can not create its
1. Redefine/Overiding objects. Abstract classes are often used to
define "Generic concepts", playing the role of a basic
2. Abstract class class for others "detailed" classes.
3. Single inheritance and multi-inheritance • Using keyword abstract
public abstract class Product
4. Interface {
// contents
}

43

2. Abstract Class Abstract Class


• Can not create objects of an abstract class • Abstract class can contain un-defined abstract methods
• Is not complete, is often used as a parent class. Its
children will complement the un-completed parts. • Derived classes must re-define (overriding) these abstract
methods

• Using abstract class plays an important role in software


design. It defines common objects in inheritance tree, but
these objects are too abstract to create their instances.

11
45 46

abstract class Shape {


2. Abstract Class (2) protected String name;
Shape(String n) { name = n; }
• To be abstract, a class needs: public String getName() { return name; }
public abstract float calculateArea();
• To be declared with abstract keyword
}
• May contain abstract methods – that have only class Circle extends Shape {
signatures without implementation private int radius;
• public abstract float calculateArea(); Circle(String n, int r){
super(n);
• Child classes must implement the details of abstract
radius = r;
methods of their parent class à Abstract classes can
}
not be declared as final or static.
• Ifa class has one or more abstract methods, public float calculateArea() {
it must be an abstract class float area = (float) (3.14 * radius * radius);
return area;
} Child class must override all the abstract methods of its
} parent class

47 48

Example of abstract class Example of abstract class (2)


class Circle extends Action {
import java.awt.Graphics;
abstract class Action { int radius;
public Circle(int x, int y, int r) {
protected int x, y;
super(x, y); radius = r;
public void moveTo(Graphics g,
}
int x1, int y1) {
public void draw(Graphics g) {
erase(g);
System out println("Draw circle at ("
x = x1; y = y1;
+ x + "," + y + ")");
draw(g);
g.drawOval(x-radius, y-radius,
}
2*radius, 2*radius);
}
public void erase(Graphics g) {
abstract public void erase(Graphics g);
System.out.println("Erase circle at ("
abstract public void draw(Graphics g);
} + x + "," + y + ")");
// paint the circle with background color...
}
}

12
Abstract Class Abstract Class
abstract class Point { abstract class ColoredPoint extends Point {
int color;
private int x, y;
public ColoredPoint(int x, int y, int color) {
public Point(int x, int y) { super(x, y); this.color = color; }
this.x = x; }
this.y = y;
} class SimpleColoredPoint extends ColoredPoint {
public SimpleColoredPoint(int x, int y, int color){
public void move(int dx, int dy) { super(x,y,color);
x += dx; y += dy; }
plot(); public void plot() {
} ...
// code to plot a SimplePoint
public abstract void plot();
}
} }

52

Abstract Class Outline


• Class ColoredPoint does not implement source code for
the method plot(), hence it must be declared as abstract 1. Redefine/Overiding
2. Abstract class
• Can only create objects of the class SimpleColoredPoint.
3. Single inheritance and multi-inheritance
• However, we can have:
4. Interface
Point p = new SimpleColoredPoint(a, b, red); p.plot();

13
53

Multiple and Single Inheritances Problems in Multiple Inheritance


Name clashes on
• Multiple Inheritance Repeated inheritance
attributes or operations
• A class can inherit several other classes
• C++ supports multiple inheritance
A B C
• Single Inheritance SomeClass
• A class can inherit only one other class Animal FlyingThing
• Java supports only single inheritance + color + color
• à Need to add the notion of Interface D + getColor () + getColor () Animal FlyingThing
+ color + color
+ getColor () + getColor ()
Bird

A E F Bird

D
Resolution of these problems is implementation-dependent.

55

Outline Mix-in inheritance

1. Redefine/Overiding • In this inheritance, a "class" will provide some functions in


order to mix with other classes.
2. Abstract class • A mixed class often re-uses some functions defined in the
provider class but also inherits from another class.
3. Single inheritance and multi-inheritance
• Is a mean that allows objects without relation in the
4. Interface hierarchy tree can communicate to each other.
• In Java the mix-in inheritance is done via Interface

14
Interface Interface
• Interface: Corresponds to different implementations.
2DShape 3DShape
• Defines the border:
Drawable • What How
• Declaration and Implementation.

Circle Rectangle Sphere Cube

Square

Interface Example
• Interface does not implement any methods but defines the • Class Bicycle – Class StoreKeeper:
design structure in any class that uses it. • StoreKeepers does not care about the characteristics what
they keep, they care only the price and the id of products.
• An interface: 1 contract – in which software development • Class AutonomousCar– GPS:
teams agree on how their products communicate to each
• Car manufacturers produce cars with features: Start, Speed-
other, without knowing the details of product
up, Stop, Turn left, Turn right,..
implementation of other teams.
• GPS: Location information, Traffic status – Making decisions
for controlling car
- How does GPS control both car and space craft?

15
Class OperateBMW760i
Interface OperateCar // Car Manufacturer
public interface OperateCar { public class OperateBMW760i implements OperateCar {

// Constant declaration– if any


// cài đặt hợp đồng định nghĩa trong giao diện
// Method signature int signalTurn(Direction direction, boolean signalOn) {
int turn(Direction direction, // An enum with values RIGHT, LEFT //code to turn BMW's LEFT turn indicator lights on
double radius, double startSpeed, double endSpeed); //code to turn BMW's LEFT turn indicator lights off
int changeLanes(Direction direction, double startSpeed, double
//code to turn BMW's RIGHT turn indicator lights on
endSpeed);
int signalTurn(Direction direction, boolean signalOn); //code to turn BMW's RIGHT turn indicator lights off
int getRadarFront(double distanceToCar, double speedOfCar); }
int getRadarRear(double distanceToCar, double speedOfCar);
...... // Các phương thức khác, trong suốt với các clients của
// Signatures of other methods interface
}
}

Shape Action 63 64
#x: int
#name: String
#y: int

4. Interface
+getName():String
+draw(Graphics)
+calculateArea():float
+moveTo(Graphics,int, int)
+erase(Graphics)

• Allows a class to inherit (implement) multiple interfaces at


Circle
the same time.
-radius: float

+calculateArea():float • Can not directly instantiate


+draw(Graphics)
+erase(Graphics)

<<interface>>
Shape Actable
#name: String #x:int #y:int
+draw(Graphics)
+getName():String
+moveTo(Graphics,int, int)
+calculateArea():float +erase(Graphics)

Circle
-radius:float

+calculateArea():float
+draw(Graphics)
+moveTo(Graphics,int,int)
+erase(Graphics)

16
66

Interface – Technique view (JAVA) 4. Interface (2)


• An interface can be considered as a class that • To become an interface, we need
• Its methods and attributes are not explicitly public • To use interface keyword to define
• Its attributes are static and final • To write only:
• Its methods are abstract • method signature
• static & final attributes

• Implementation class of interface


• Either abstract class
• Or must implement all the methods of the interface.

67 68

4. Interface (3) Example


• Java syntax: Shape
<<interface>>
Actable
• SubClas extends SuperClass implements #name: String #x:int #y:int
+draw(Graphics)
+getName():String
ListOfIntefaces +calculateArea():float
+moveTo(Graphics,int, int)
+erase(Graphics)
• SubInterface extends SuperInterface

• Example: Circle
public interface Symmetrical {…} -radius:float

public interface Movable {…} +calculateArea():float


+draw(Graphics)
public class Square extends Shape +moveTo(Graphics,int,int)
+erase(Graphics)
implements Symmetrical, Movable {
...
}

17
69 70
class Circle extends Shape implements Actable {
import java.awt.Graphics; private int radius;
abstract class Shape { public Circle(String n, int x, int y, int r){
protected String name; super(n, x, y); radius = r;
protected int x, y; }
public float calculateArea() {
Shape(String n, int x, int y) { float area = (float) (3.14 * radius * radius);
name = n; this.x = x; this.y = y; return area;
} }
public void draw(Graphics g) {
public String getName() {
System out println("Draw circle at ("
return name; + x + ," + y + ")");
} g.drawOval(x-radius,y-radius,2*radius,2*radius);
public abstract float calculateArea(); }
public void moveTo(Graphics g, int x1, int y1){
} erase(g); x = x1; y = y1; draw(g);
interface Actable { }
public void draw(Graphics g); public void erase(Graphics g) {
public void moveTo(Graphics g, int x1, int y1); System out println( Erase circle at ("
+ x + ," + y + ")");
public void erase(Graphics g);
// paint the region with background color...
} }
}

72

Disadvantages of Interface in solving Multiple Example


Inheritance problems interface Shape2D {
double getArea();
• Does not provide a } Shape2D Shape Shape3D
nature way for situations
without inheritance interface Shape3D {
conflicts double getVolume();
} Circle Sphere
• Inheritance is to re-uses
class Point3D {
source code but Interface
double x, y, z;
can not do this
Point3D(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
}

18
74
3/11/2010

abstract class Shape { class Sphere extends Shape

}
abstract void display(); implements Shape3D {
Point3D center;
double radius;
interface Comparable /java.lang
class Circle extends Shape Sphere(Point3D center, double radius) { Result :
implements Shape2D { this.center = center;
this.radius = radius; Circle
Point3D center, p; // p is an point on
circle } 3.141592653589793
Sphere
Circle(Point3D center, Point3D p) { public void display() {
4.1887902047863905
System.out.println("Sphere");
this.center = center; }
this.p = p;
} public double getVolume() {
return 4 * Math.PI * radius * radius * radius / 3;
public void display() { }
}
System.out.println("Circle");
} class Shapes {

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


double dx = center.x - p.x;
Circle c = new Circle(new Point3D(0, 0, 0), new
double dy = center.y - p.y; Point3D(1, 0, 0));
double d = dx * dx + dy * dy; c.display();
double radius = Math.sqrt(d); System.out.println(c.getArea());
return Math.PI * radius * radius; Sphere s = new Sphere(new Point3D(0, 0, 0), 1);
s.display();
} System.out.println(s.getVolume());
} }}

Application Application

19

Anda mungkin juga menyukai