0% found this document useful (0 votes)
64 views

07-Abstract Class and Interface

The document outlines key concepts related to object-oriented programming including: 1. Redefining or overriding methods in child classes. 2. Abstract classes and how they can contain abstract methods without an implementation that must be defined in subclasses. 3. Differences between single and multiple inheritance and how interfaces allow for multiple inheritance in Java.

Uploaded by

Trung Đặng
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)
64 views

07-Abstract Class and Interface

The document outlines key concepts related to object-oriented programming including: 1. Redefining or overriding methods in child classes. 2. Abstract classes and how they can contain abstract methods without an implementation that must be defined in subclasses. 3. Differences between single and multiple inheritance and how interfaces allow for multiple inheritance in Java.

Uploaded by

Trung Đặng
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/ 16

2

Outline

1. Redefine/overriding
OBJECT-ORIENTED LANGUAGE AND THEORY
2. Abstract class
7. ABSTRACT CLASS AND INTERFACE
3. Single inheritance and multi-inheritance
4. Interface

1 2

3 4

Outline 1. Re-definition or Overriding


• A child
class can define a method with the same
1. Redefine/overriding 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)

3 4

1
5 6

• class A { • ParentClass: aMethod() => overridden method


a(){ …. } • ChildClass1: aMethod(), aMethod(String) => Overloading
• ChildClass2: aMethod() => Overriding/Redefinition method
}

• class B extends A { • ChildClass1 cc1 = new ChildClass1();


a(String) {} • cc1.aMethod(); cc1.aMethod(“a string”);
} • ChildClass2 cc2 = new ChildClass2();
• cc2.aMethod();
… B b = new B();
b.a();
b.a(“test”);

5 6

7 8

1. Re-definition or Overriding (2)


• Overriding method will replace or add more details to the • this() and this => current object
overriden method in the parent class
• Objects of child class will use the re-defined method • super() => Constructor of the parent class
• super: object of the parent class

7 8

2
9 10
class Shape {
protected String name;
class Square extends Shape {
Shape(String n) { name = n; } private int side;
public String getName() { return name; } Square(String n, int s) {
public float calculateArea() { return 0.0f; } super(n);
}
side = s;
class Circle extends Shape {
private int radius; }
Circle(String n, int r){ public float calculateArea() {
super(n); float area = (float) side * side;
radius = r; return area;
}
}
public float calculateArea() { }
float area = (float) (3.14 * radius * radius);
return area;
}
}

9 10

11 12

Class Triangle this and super


class Triangle extends Shape { • this and super can use non-static
private int base, height; methods/attributes and constructors
Triangle(String n, int b, int h) { • this: searching for methods/attributes in the
super(n); current class
base = b; height = h; • super: searching for methods/attributes in the
} direct parent class
public float calculateArea() {
• Keyword super allows re-using the source-code
float area = 0.5f * base * height;
of a parent class in its child classes
return area;
}
}

11 12

3
13 14

package abc;
public class Person { Overriding Rules
private String name;
private int age;
public String getDetail() {
• Overriding methods must have:
String s = name + "," + age; • An argument list that is the same as the overriden
return s; method in the parent class => signature
}
• The same return data types as the overriden method
private void pM(){}
} in the parent class
• Can not override:
import abc.Person;
public class Employee extends Person { • Constant (final) methods in the parent class
double salary; • Static methods in the parent class
public String getDetail() {
String s = super.getDetail() + "," + salary • Private methods in the parent class
return s;
}
}
13 14

15 16

Overriding Rules (2) Example


class Parent {
• Accessibility can not be more restricted in a
public void doSomething() {}
child class (compared to in its parent class) protected int doSomething2() {
• For example, if we override a protected method, the return 0; cannot override: attempting to use
new overriding method can only be protected or } incompatible return type
public, and can not be private. }
class Child extends Parent {
protected void doSomething() {}
protected void doSomething2() {}
}
cannot override: attempting to assign
weaker access privileges; was public

15 16

4
17 18

Example: private Outline


class Parent {
public void doSomething() {} 1. Redefine/overriding
private int doSomething2() {
return 0; 2. Abstract class
}
} 3. Single inheritance and multi-inheritance
class Child extends Parent {
public void doSomething() {}
4. Interface
private void doSomething2() {}
}

17 18

20

Abstract Class 2. Abstract Class


• An abstract class is a class that we can not create its • Can not create objects of an abstract class
objects. Abstract classes are often used to • Is not complete, is often used as a parent class. Its
define "Generic concepts", playing the role of a basic children will complement the un-completed parts.
class for others "detailed" classes.
• Using keyword abstract
public abstract class Product
{
// contents
}
…Product aProduct = new Product(); //error

concrete class vs. abstract class

19 20

5
22

Abstract Class 2. Abstract Class (2)


• Abstract class can contain abstract methods • To be abstract, a class needs:
• To be declared with abstract keyword
• Derived classes that are no abstract must implement
• May contain abstract methods – that have only
these abstract methods
signatures without implementation
• public abstract float calculateArea();
• Using abstract class plays an important role in software
• Child classes must implement the details of abstract
design. It defines common objects in inheritance tree, but
these objects are too abstract to create their instances. methods of their parent class à Abstract classes can
not be declared as final or static.
• Ifa class has one or more abstract methods,
it must be an abstract class

21 22

23 24

abstract class Shape {


protected String name; Example of abstract class
Shape(String n) { name = n; }
public String getName() { return name; } import java.awt.Graphics;
public abstract float calculateArea(); abstract class Action {
} protected int x, y;
class Circle extends Shape { public void moveTo(Graphics g,
int x1, int y1) {
private int radius;
erase(g);
Circle(String n, int r){ x = x1; y = y1;
super(n); draw(g);
radius = r; }
}

public float calculateArea() { public abstract void erase(Graphics g);


float area = (float) (3.14 * radius * radius); public abstract void draw(Graphics g);
return area; }
} Child class must override all the abstract methods of its ..Circle c = new Circle();
} parent class c.moveTo(...);

23 24

6
25

Example of abstract class (2) Abstract Class


class Circle extends Action {
int radius; abstract class Point {
public Circle(int x, int y, int r) { private int x, y;
super(x, y); radius = r; public Point(int x, int y) {
}
public void draw(Graphics g) { this.x = x;
System out println("Draw circle at (" this.y = y;
+ x + "," + y + ")"); }
g.drawOval(x-radius, y-radius,
2*radius, 2*radius); public void move(int dx, int dy) {
} x += dx; y += dy;
public void erase(Graphics g) { plot();
System.out.println("Erase circle at ("
+ x + "," + y + ")"); }
// paint the circle with background color... public abstract void plot();
} }
}

25 26

Abstract Class Abstract Class


abstract class ColoredPoint extends Point { • Class ColoredPoint does not implement source code for
int color;
the method plot(), hence it must be declared as abstract
public ColoredPoint(int x, int y, int color) {
super(x, y); this.color = color; }
} • Can only create objects of the class SimpleColoredPoint.

class SimpleColoredPoint extends ColoredPoint {


public SimpleColoredPoint(int x, int y, int color){ • However, we can have:
super(x,y,color); Point p = new SimpleColoredPoint(a, b, red); p.plot();
}
public void plot() {
...
// code to plot a SimplePoint
}
}

27 28

7
29 30

Outline
• abstract class A {
abstract void a(); 1. Redefine/overriding
•} 2. Abstract class
• class B extend A {
•} 3. Single inheritance and multi-inheritance
4. Interface

29 30

31

Multiple and Single Inheritances Problems in Multiple Inheritance


Name clashes on
• Multiple Inheritance attributes or operations Repeated inheritance
• 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

Resolution of these problems is implementation-dependent.


D

31 32

8
33

Outline Interface

1. Redefine/overriding 2DShape 3DShape

Drawable
2. Abstract class
3. Single inheritance and multi-inheritance Circle Sphere
Rectangle Cube
4. Interface

Square

33 35

Interface Interface
• Interface: Corresponds to different implementations. • Interface does not implement any methods but defines the
• Defines the border: design structure in any class that uses it.
• What and How
• Declaration and Implementation. • An interface: 1 contract – in which software development
teams agree on how their products communicate to each
other, without knowing the details of product
implementation of other teams.

36 37

9
Example Interface OperateCar
• Class Bicycle – Class StoreKeeper: public interface OperateCar {
• StoreKeepers does not care about the characteristics what
// Constant declaration– if any
they keep, they care only the price and the id of products.
• Class AutonomousCar– GPS: // Method signature
• Car manufacturers produce cars with features: Start, Speed- int turn(Direction direction, // An enum with values RIGHT, LEFT
up, Stop, Turn left, Turn right,.. double radius, double startSpeed, double endSpeed);
• GPS: Location information, Traffic status – Making decisions int changeLanes(Direction direction, double startSpeed, double
for controlling car endSpeed);
int signalTurn(Direction direction, boolean signalOn);
- How does GPS control both car and space craft?
int getRadarFront(double distanceToCar, double speedOfCar);
int getRadarRear(double distanceToCar, double speedOfCar);
......
// Signatures of other methods
}

38 39

Shape Action 41
#x: int
#name: String
Class OperateBMW760i +getName():String
+calculateArea():float
#y: int
+draw(Graphics)
+moveTo(Graphics,int, int)
// Car Manufacturer +erase(Graphics)

public class OperateBMW760i implements OperateCar {


Circle
-radius: float
// cài đặt hợp đồng định nghĩa trong giao diện +calculateArea():float
int signalTurn(Direction direction, boolean signalOn) { +draw(Graphics)
+erase(Graphics)
//code to turn BMW's LEFT turn indicator lights on <<interface>>
//code to turn BMW's LEFT turn indicator lights off Shape Actable
#name: String #x:int #y:int
//code to turn BMW's RIGHT turn indicator lights on +getName():String +draw(Graphics)
+moveTo(Graphics,int, int)
+calculateArea():float
//code to turn BMW's RIGHT turn indicator lights off +erase(Graphics)

}
Circle
// Các phương thức khác, trong suốt với các clients của -radius:float

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

40 41

10
42

4. Interface Interface – Technical view (JAVA)


• Allows a class to inherit (implement) multiple interfaces at • An interface can be considered as a “class” that
the same time. • Its methods and attributes are implicitly public
• Can not directly instantiate • Its attributes are static and final (implicitly)
• Its methods are abstract

interface TVInterface {
public void turnOn();
public void turnOff();
public void changeChannel(int i);
}
class PanasonicTV implements TVInterface{
public void turnOn() { …. }
}

42 43

44 45

4. Interface (2) 4. Interface (3)


• To become an interface, we need
• Java syntax:
• To use interface keyword to define
• To write only: • SubClass extends SuperClass implements
• method signature ListOfIntefaces
• static & final attributes • SubInterface extends SuperInterface
• Implementation class of interface
• Example:
• Abstract class
public interface Symmetrical {…}
• Concrete class: Must implement all the methods of the interface
public interface Movable {…}
public class Square extends Shape
implements Symmetrical, Movable {
...
}

44 45

11
46 47

import java.awt.Graphics;
Example abstract class Shape {
protected String name;
protected int x, y;
<<interface>>
Shape Actable Shape(String n, int x, int y) {
#name: String #x:int #y:int name = n; this.x = x; this.y = y;
+getName():String +draw(Graphics)
+calculateArea():float
+moveTo(Graphics,int, int) }
+erase(Graphics)
public String getName() {
return name;
Circle }
-radius:float public abstract float calculateArea();
+calculateArea():float }
+draw(Graphics)
+moveTo(Graphics,int,int) interface Actable {
+erase(Graphics)
public void draw(Graphics g);
public void moveTo(Graphics g, int x1, int y1);
public void erase(Graphics g);
}

46 47

48 49
class Circle extends Shape implements Actable {
private int radius;
public Circle(String n, int x, int y, int r){
super(n, x, y); radius = r;
Abstract class vs. Interface
}
public float calculateArea() { • May or may not • Can contain only
float area = (float) (3.14 * radius * radius);
return area; contain abstract method signature
} methods, can contain • Can contain only
public void draw(Graphics g) {
System out println("Draw circle at ("
instance methods public functions
+ x + “," + y + ")");
• Can contain protected without implementation
g.drawOval(x-radius,y-radius,2*radius,2*radius);
} and static methods • Can contains only
public void moveTo(Graphics g, int x1, int y1){
erase(g); x = x1; y = y1; draw(g); • Can contain final and constant attributes
} non-final attributes • A class can inherite
public void erase(Graphics g) {
System out println(“Erase circle at (" • A class can inherit only multiple interfaces
+ x + “," + y + ")"); one abstract class
// paint the region with background color...
}
}
48 49

12
50

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;
}
}

50 51

3/11/2010
52

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) {
implements Shape2D { this.center = center;
this.radius = radius; Result :
Point3D center, p; // p is an point on
circle } Circle
3.141592653589793
Circle(Point3D center, Point3D p) { public void display() { Sphere
System.out.println("Sphere");
this.center = center; 4.1887902047863905
}
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());
} }
}

52 53

13
Application Application

54 55

56 57

Java 8 Interface – default methods


https://gpcoder.com/3854-interface-trong-java-8-default-
method-va-static-method/

public interface Shape {

void draw();

default void setColor(String color) {


System.out.println("Draw shape with color " + color);
}
}

56 57

14
59

Multiple Inheritance Multiple Inheritance


interface Interface1 { interface Interface3 {
default void doSomething() { default void doSomething() {
System.out.println("doSomething1"); System.out.println("Execute in Interface3");
} }
} }

interface Interface2 { class Parent {


default void doSomething() { public void doSomething() {
System.out.println("doSomething2"); System.out.println("Execute in Parent");
} }
} }

public class MultiInheritance implements Interface1, Interface2 { public class MultiInheritance2 extends Parent implements Interface3 {
@Override public static void main(String[] args) {
public void doSomething() { MultiInheritance2 m = new MultiInheritance2();
Interface1.super.doSomething(); m.doSomething(); // Execute in Parent
} }
} }

58 59

60 61

Java 8 interface – Static methods Static method


interface Vehicle { interface Interface3 {
default void print() { default void doSomething() {
if (isValid()) System.out.println("Execute in Interface3");
System.out.println("Vehicle printed"); }
} }
static boolean isValid() {
System.out.println("Vehicle is valid"); abstract class Parent {
return true; public void doSomething() {
System.out.println("Execute in Parent");
} }
void showLog(); public static void test() {
} System.out.println("test");
}
}
public class Car implements Vehicle {
@Override public class MultiInheritance2 extends Parent implements Interface3 {
public void showLog() { public static void main(String[] args) {
print(); MultiInheritance2 m = new MultiInheritance2();
Vehicle.isValid(); m.test(); // OK
} }
} }

60 61

15
62 63

Static method Static method


interface Interface3 { interface Interface3 {
default void doSomething() { default void doSomething() {
System.out.println("Execute in Interface3"); System.out.println("Execute in Interface3");
} }
public static void test() {
} System.out.println("test");
}
abstract class Parent { }
public void doSomething() {
System.out.println("Execute in Parent"); abstract class Parent {
} public void doSomething() {
public static void test() { System.out.println("Execute in Parent");
System.out.println("test"); }
} }
}
public class MultiInheritance2 extends Parent implements Interface3 {
public class MultiInheritance2 extends Parent implements Interface3 { public static void main(String[] args) {
public static void main(String[] args) { MultiInheritance2 m = new MultiInheritance2();
MultiInheritance2 m = new MultiInheritance2();
m.test(); // ERROR!!!
MultiInheritance2.test(); // OK }
} }
}

62 63

64

Static method
interface Interface3 {
default void doSomething() {
System.out.println("Execute in Interface3");
}
public static void test() {
System.out.println("test");
}
}
abstract class Parent {
public void doSomething() {
System.out.println("Execute in Parent");
}
}
public class MultiInheritance2 extends Parent implements Interface3 {
public static void main(String[] args) {
MultiInheritance2 m = new MultiInheritance2();
MultiInheritance2.test(); // ERROR!!!
}
}

64

16

You might also like