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

03_OOP_2-LT

Chapter 3 discusses Object-Oriented Programming (OOP) concepts in Java, focusing on inheritance and polymorphism. It explains how inheritance allows classes to inherit properties and methods from parent classes, and describes single and multi-level inheritance structures. The chapter also covers polymorphism, including method overloading and overriding, as well as abstraction through abstract classes and interfaces.

Uploaded by

ndm211005
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)
2 views

03_OOP_2-LT

Chapter 3 discusses Object-Oriented Programming (OOP) concepts in Java, focusing on inheritance and polymorphism. It explains how inheritance allows classes to inherit properties and methods from parent classes, and describes single and multi-level inheritance structures. The chapter also covers polymorphism, including method overloading and overriding, as well as abstraction through abstract classes and interfaces.

Uploaded by

ndm211005
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/ 42

Chapter 3.

OOP – CLASSES AND OBJECTS IN JAVA

INHERITANCE AND POLYMORPHISM


1. Inheritance in Java
❑ Inheritance is one of the most important features in OOP. It allows
to build a relationship between two classes, including a parent
class (Super class) and a child class (Sub class)

❖ Examples of parent class and child classes

Super class​​ Sub class​​


Shape Rectangle, Oval, Diamond
Person Student, Teacher, Worker, Manager
Animal Dog, Cat, Duck
1. Inheritance in Java
❑ When inheriting, the child class will get:
❖ Inherits all the properties and methods that the parent
class allows
❖ Defines additional properties and methods of its own

❖ Redefine methods to match subclass

❑ Benefits of inheritance :
❖ Reusability of code – reusability

❖ Allows program extensibility – changes only affect subclasses,

not the parent class or core parts of the program –


extensibility
❖ Easy access for initial design and later design expansion –

designability .​
1. Inheritance in Java
❑ In Java, only single inheritance is supported but not multiple
inheritance. Multiple inheritance in Java is designed based
on the concept of interface.

ParentClass ParentClass ParentClass

ChildClass ChildClass_1
ChildClass_1 ChildClass_2

1) Single
ChildClass_2 3) Hierarchical

2) MultiLevel
4
1. Inheritance in Java
Syntax for creating an inherited class in Java :
public ParentClass {

}
public ChildClass extends ParentClass {

}

Note: access to the properties and methods of the parent class depends
on the access scope defined

5
1. Inheritance in Java
public ParentClass {

}
public ChildClass_1 extends ParentClass { 2) MultiLevel

}
public ChildClass_2 extends ChildClass_1 {

}

public ParentClass {

}
public ChildClass_1 extends ParentClass { 3) Hierarchical

}
public ChildClass_2 extends ParentClass {

}
6
1. Inheritance in Java – Example
public class Parent { ❑ Single Inheritance
public void color (){
System.out.println(“blue”);}
}
public class Child extends Parent {
public void show (){
System.out.print(“This is an apple ”);}
}
public class Test {
public static void main(String args[]) {
Child c = new Child ();
c. show ();
c. color ();
Result This is a green apple
}
} 7
1. Inheritance in Java
❑ MultiLevel
public class Parent { public class Test {
public void color (){ public static void main(String
System.out.println(“ blue ”);} args[]) {
} Child2 c2 = new Child2 ();
c2. show1 ();
public class Child1 extends Parent {
c2. color ();
public void show1 (){
c2. show2 ();
System.out.print(“ This is an apple ”);}
}
}
}
public class Child2 extends Child1 {
public void show2 (){
System.out.println(“ Made in Vietnam ”);}
} This is a green apple
Result
Made in Vietnam

8
1. Inheritance in Java
❑ Hierarchical
public class Parent { public class Test {
public void color(){ public static void main(String
System.out.println(“blue”);} args[]) {
} Child1 c1 = new Child1 ();
c1. show1 ();
public class Child1 extends Parent { c1. color ();
public void show1(){
System.out.print(“This is an apple ”);} Child2 c2 = new Child2 ();
} c2. show2 ();
c2. color ();
public class Child2 extends Parent { }
public void show2(){ }
System.out.print(“This is an orange”);}
This is a green apple
} Result
This is a green orange.
9
1. Inheritance in Java
Some keywords used:

❑ this: used to refer to the current class instance


❑ this(): to call a constructor from another constructor of the class

❑ super: used to refer to the nearest parent class instance

❑ @Override: used in case of redefining methods to suit subclasses

❑ final:
❖ class: not allow creating subclasses derived from this class.
❖ method : not allow child class to override parent class method

10
1. Inheritance in Java
Constructor in inheritance
• Jaw create Are not Okay excess plan
• Jaw create belong to right subclass​ call next jaw create belong to
parent class via super(<ds reference ) number >)
• Word call next jaw create other Right To be sentence command
head fairy in constructor
public class Student extends Person{
public String studentId ;

public Student(String name, String address, String studentId){


super(name, address);
this.studentId = studentId ;
}
}

• In school fit parent class has jaw create wear determine then
Are not need call one way explicit
11
1. Inheritance in Java – Example
1. Build a 2D point layer with the following methods:
▪ Show point coordinates
▪ Calculate the distance from the point to the origin
2. Build a 3D point class that inherits the 2D point class with the method:
▪ Show point coordinates
▪ Calculate the distance from the point to the origin
3. Build the main program:
▪ Create 2D point list and 3D point list
▪ Calculate the sum of the distances of 2D points to the origin
▪ Calculate the sum of the distances of 3D points to the origin

12
1. Inheritance in Java
ParentClass ChildClass

Point2D Point3D
• attributes •attributes
ox o x, y
oy oz
• constructors •constructors
o getX(), setX() •getX(), getY()
o getY(), setY() •setX(), setY()
• methods: •getZ(), setZ()
(x,y) o show() •methods:
o distance() oshow() (x,y,z)
𝑑= 𝑥2 + 𝑦2
odistance() 𝑑= 𝑥2 + 𝑦2 + 𝑧2

13
1. Inheritance in Java – Example
public class Point2D {
private double x,y ; attributes
public Point2D (double x , double y ){
this.x = x ;
this.y = y ; constructor
}
public double getX (){
return x ;
}
public void setX (double x ){
this.x = x ; getters and setters
}
public double getY (){
return y ;
}
public void setY (double y ){
this.y = y ;
} methods
public String show (){
return "Point2D ["+ this.x +","+ this.y +"]";
}
public double distance (){
return Math.sqrt( this.x * this.x+this.y * this.y );
}
} 14
1. Inheritance in Java – Example
public class Point3D extends Point2D { Add new attribute
private double z ;
public Point3D (double x, double y, double z){
super(x,y);
this.z =z;
} Redefine the
constructor to match
public double getZ() { the subclass
return z ;
} add getters and setters for new
public void setZ (double z){ properties of subclass
this.z =z;
}
redefine
@Override
methods
public String show() {
return "Point3D [" + this.getX()+ "," + this.getY()+ "," + this.z
+"]";
}
@Override
public double distance() {
return Math.sqrt(super.distance() * super.distance() + this.z * this.z
);
}
} 15
1. Inheritance in Java – Example
public static void main(String[] args) {
List<Point2D> listPoint2D =new ArrayList<Point2D>();
Point2D p1_2D = new Point2D(1.0,4.0);
Point2D p2_2D = new Point2D(3.0,6.0);
Point2D p3_2D = new Point2D(4.0,7.0);
//add elements to the list
listPoint2D.add(p1_2D);
listPoint2D.add(p2_2D);
listPoint2D.add(p3_2D);
for(Point2D point:listPoint2D){
System.out.println(point.show());
}
//distance calculation
double sum2D=0.0;
for(Point2D point:listPoint2D){
sum2D +=point.distance();
}
System.out.println("Distance of Point2D: " +sum2D);
}

Result:
Point2D [1.0,4.0]
Point2D [3.0,6.0]
Point2D [4.0,7.0]
Distance of Point2D: 18.89356730641558 16
1. Inheritance in Java – Example
List<Point3D> listPoint3D =new ArrayList<Point3D >();
Point3D p1_3D = new Point3D(1.0,4.0,7.0);
Point3D p2_3D = new Point3D(3.0,6.0,9.0);
Point3D p3_3D = new Point3D(5.0,7.0,3.0);
//add elements to the list
listPoint3D.add(p1_3D);
listPoint3D.add(p2_3D);
listPoint3D.add(p3_3D);
for(Point3D point:listPoint3D){
System.out.println(point.show());
}
//distance calculation
double sum3D=0.0;
for(Point3D point:listPoint3D){
sum3D +=point.distance();
}
System.out.println("Distance of Point3D: " + sum3D);
Result:
Point3D [1.0,4.0,7.0]
Point3D [3.0,6.0,9.0]
Point3D [5.0,7.0,3.0]
Distance of Point3D: 28.459444144102086 17
2. Polymorphism in Java
❑ Polymorphism is one of the four fundamental properties of OOP
programming in Java, allowing different objects to perform the same
functionality in different ways.

18
2. Polymorphism in Java
❑ There are two types of polymorphism in java, compile time polymorphism
and runtime polymorphism. We can implement polymorphism in java by
method overloading and method overriding.

19
2. Polymorphism in Java

Method Overriding Method Overloading


When a child class inherits a method When a class has multiple methods with
from its parent class and needs to the same name that perform the same
redefine it accordingly purpose
Overridden method with same name, Methods must have different parameter
same return data type same parameters types or number of parameters.

It is not possible to overload a method by


The modifier scope of a method in a
just changing the return type of the
child class must be within the modifier
method because it is not known which
scope of the parent class.
method will be called.
Java automatically casts the argument if
the value of the passed argument does
Do not override static methods
not match the data type of the defined
parameter.

20
2. Polymorphism in Java
❑ Type casting diagram

character

byte short int long

float double

21
2. Polymorphism in Java – Example

Add method to calculate distance between two 2D points


ParentClass ChildClass

Point2D Point3D
• attributes •attributes
ox ox, y
oy oz
• constructors •constructors
o getX(), setX() Method •getX(), getY()
o getY(), setY() overriding
•setX(), setY()
• methods: •getZ(), setZ()
o show() •methods:
o distance() oshow()
o distance(double x, double y) o distance()
Method
overloading
22
2. Polymorphism in Java – Example

public class Point2D {


public String show (){ Method
return "Point2D ["+ this.x +","+ this. y +"]"; overloading
}
public double distance (){
return Math.sqrt( this.x * this.x+this.y * this.y );
}
public double distance (double x, double y){
double dx=(this.getX()-x);
double dy=(this.getX()-y);
return Math.sqrt(dx*dx+dy*dy); Method
} overriding
}

public class Point3D extends Point2D {


@Override
public double distance() {
return Math.sqrt( super .distance ()* super .distance () +
this.z * this.z );
}
}
23
2. Polymorphism in Java – Exercises

Student
Build a program with classes:
• id, full name, date of birth,
IT student class, Economics student gender, politics, law,...
class extends Student class • Constructors, gets, sets
• methods:
o Input information
o Show information

IT Student Economics Student


• CTDL_GT, RR Math, • Microeconomics,
Database, OOP Macroeconomics, Economic
Programming,.. Law, …
• Constructors, gets, sets • Constructors, gets, sets
• methods: • methods:
o Input information o Input information
o Show information o Show information
o Average score o Average score
o Learning Classification o Learning Classification
24
Chapter 3. OOP – CLASSES AND OBJECTS IN JAVA

ABSTRACT
3. Abstraction in Java​

26
3. Abstraction in Java​

Purpose:
▪ Allows hiding detailed settings, only showing usage to
users, helping programmers implement complex
operations based on behaviors provided by objects.
▪ For example:
✓ Applications: Frameworks and libraries provide an abstraction
that allows us to build on top of it to develop our own
applications.
▪ In Java, the abstraction approach is based on
inheritance with:
• Abstract class
• Interface

27
3. Abstraction in Java​

28
3. Abstraction in Java​
❖ Abstract
➢ Abstract class does not allow instantiation of objects from
abstract class.
➢ Derived classes of abstract classes can:
✓ abstract class → No need to implement abstract methods.
✓ regular class → It is required to implement abstract methods of the class.
abstract
➢ class can be inherited → Inherit a regular class or an
abstract class.
➢ The scope of an abstract method cannot be private because
it needs to be redefined in a derived class.
➢ Since Java 7, abstract class may or may not have abstract
methods but abstract class cannot create instance even if it
does not have abstract methods.

29
3. Abstraction in Java​

30
3. Abstraction in Java​

Abstract Interface

Abstract classes have abstract methods Interface has only abstract methods.
(without function bodies) or non - From Java 8, it has additional default and
abstract methods (with jaw). static methods.

Abstract classes do not support multiple


Interface supports
inheritance .
Abstract class has final , non- final, static Interface has only static variables and final
and non- static .

Abstract classes can provide Interface cannot provide implementation


implementations for interfaces for methodsofabstract class

The abstract keyword is used to abstract The interface keywordis used to


the declared class. declare interface

31
Example
❑ Interface – abstract class
To build the Paint application that allows users to perform
operations with shapes including: Point, Circle, Line, Triangle,
Rectangle, ... people build the space of shapes with the OOP
approach.
➢ Building Interface Shape with methods:
✓ Calculation: area , perimeter , distance , ..

✓ Transformation: move , rotate , zoom ,

➢ Based on Interface Shape, build classes corresponding to


objects.

32
Example
Interface – abstract class
1. Set <<interface>>
✓ Define Shape methods ( calculate + variable )
2. Implement the classes
✓ Point, Circle, Line, Triangle, Rectangle …
✓ attributes/constructors/getters and setters/toString

✓ area/perimeter/distance/move/rotate/zoom

3. Building the main program:


✓ Generate a set of random shapes and put them into a list for
management
✓ Display a list of created shapes
✓ Calculate the total perimeter/area of ​created shapes and find the
shape with the largest/smallest area
✓ Transform shapes by allowing them to be scaled …
33
Exercise-1
Use the concepts of inheritance, polymorphism, and access scope for properties and
methods to complete the exercise.
1. Complete the 2D point class with the following methods:
▪ Show point coordinates
▪ Calculate the distance from the point to the origin
▪ Calculate the distance between 2 points
▪ Determine the point of symmetry about the origin
2. Complete the 3D point class that inherits the 2D point class with the method:
▪ Show point coordinates
▪ Redefining the method of calculating the distance from a point to the origin
▪ Calculate distance between 2 3D points
▪ Determine the point of symmetry about the origin
3. Build the main program:
▪ Create 2D point list and 3D point list
▪ Calculate the sum of distances between 2D points, the sum of distances
between 3D points
▪ Put the symmetry points in the list and display the list of points
34
Exercise-2
• Build a Person class with attributes of full name, year of birth , address and
methods to input/output the above information .
• Build a Student class that includes information like the Person class, adding
average scores and input/output information for students .
• Build a Teacher class that inherits the Person class, adding information about
the number of teaching hours and input/output methods.
• Implement the input and output methods of the Student and Teacher classes.

Expand the above exercise as follows:


✓ Add method to grade student performance
✓ Add basic salary, allowance for teachers and calculation method = salary +
allowance
✓ Perform input and display of information for n students and n teachers
Chapter 3. OOP – CLASSES AND OBJECTS IN JAVA

EXPANDED CONCEPTS
Inner/Outer class
Concept:
➢ In Java, it is allowed to declare class /interface lie in a class /
interface people call nested class → nested class
➢ The containing class is called the outer class and the declared class
inside is called the inner class.
➢ Advantage:
❖ Group classes with the same logic in one file for management.
❖ The inner class is then considered a part of the outer class so it can access the
properties/methods of the outer class even if the properties/methods are private.
❖ Saves code in accessing outer components.
➢ Disadvantages:
❖ The inner class and its methods cannot be used in other classes.
❖ Inner class references outer class so the created object is only released when
outer object is released memory waste. Inner arrays should not be used.

37
38
Inner/Outer class
✓ Static nested class
✓ Treated as a static member of the outer class→
✓ Can be accessed through the outer class.
✓ Access only static members of the outer class .

39
Inner/Outer class
✓ Non static nested class – inner class
Considered as 2 classes when compiled however
✓ Accessed through the outer class.
✓ Can access the properties/methods of the outer class .

40
Inner/Outer class
✓ Local inside class
✓ Class inside Okay declare newspaper in one direction awake
belong to class outer.
Then the inner class cannot be called fromoutside .

41
Inner/Outer class
✓ Anonymous inside class
✓ The inner class is created during the implementation of virtual
methods of an abstract class or interface

42

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy