Abstract Classes, Abstract Methods, Override Methods
Polymorphism
Software University
http://softuni.bg
SoftUni Team
Technical Trainers
1. Polymorphism
 What is Polymorphism?
 Types of Polymorphism
 Override Methods
 Overload Methods
2. Abstract Classes
 Abstract Methods
Table of Contents
2
sli.do
#java-advanced
Have a Question?
Polymorphism
4
 From the Greek
 Such as a word having several different meanings
based on the context
 Often referred to as the third pillar of OOP, after
encapsulation and inheritance
What is Polymorphism?
5
Polys
(many)
Morphe
(shape/forms)
Polymorphos
 Ability of an object to take on many forms
Polymorphism in OOP
6
public interface Animal {}
public abstract class Mammal {}
public class Person extends Mammal implements Animal {}
Person IS-A Person
Person IS-A Mammal Person IS-AN Object
Person IS-AN Animal
 Variables are saved in reference type
 You can use only reference methods
 If you need object method you need to cast it or override it
Reference Type and Object Type
7
public class Person extends Mammal implements Animal {}
Animal person = new Person();
Mammal personOne = new Person();
Person personTwo = new Person();
Reference Type Object Type
 Check if object is an instance of a specific class
if (peter.getClass() == Person.class) {
((Person) peter).getSalary();
}
Keyword - instanceof
8
Mammal george = new Person();
Person peter = new Person();
Cast to object type and use its methods
if (george instanceof Person) {
((Person) george).getSalary();
}
Check object type of person
 Runtime polymorphism
 Compile time polymorphism
Types of Polymorphism
9
public class Shape {}
public class Circle extends Shape {}
public static void main(String[] args) {
Shape shape = new Circle();
}
int sum(int a, int b, int c){}
double sum(Double a, Double b){}
Method
overloading
Method
overriding
 Also known as Static Polymorphism
 Argument lists could differ in
 Number of parameters
 Data type of parameters
 Sequence of Data type of parameters
Compile Time Polymorphism
10
static int myMethod(int a, int b) {}
static Double myMethod(Double a, Double b) {}
Method overloading
 Create a class MathOperation, which should have method add()
 Must be invoked with two, three or four integers
Problem: MathOperation
11
MathOperation
+add(int a, int b): int
+add(int a, int b, int c): int
+add(int a, int b, int c, int d): int
Check your solution here :https://judge.softuni.bg/Contests/1592/Polymorphism-Lab
Solution: Math Operation
12
public class MathOperation {
public int add(int a, int b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
public int add(int a, int b, int c, int d) {
return a + b + c + d;
}
}
 Overloading can take place in the same class or in its sub-class
 Constructors in Java can be overloaded
 Overloaded methods must have a different argument list
 Overloaded method should always be the part of the same
class (can also take place in sub class), with same name but
different parameters
 They may have the same or different return types
Rules for Overloading Method
13
 Using of override method
Runtime Polymorphism
14
public static void main(String[] args) {
Rectangle rect = new Rectangle(3.0, 4.0);
Rectangle square = new Square(4.0);
System.out.println(rect.area());
System.out.println(square.area());
}
Method
overriding
 Also known as Dynamic Polymorphism
Runtime Polymorphism
15
public class Square extends Rectangle {
@Override
public Double area() {
return this.a * this.a;
}
}
Method overriding
public class Rectangle {
public Double area() {
return this.a * this.b;
}
}
 Overriding can take place in sub-class
 Argument list must be the same as that of the parent method
 The overriding method must have same return type
 Access modifier cannot be more restrictive
 Private, static and final methods can NOT be overriden
 The overriding method must not throw new or broader
checked exceptions
Rules for Overriding Method
16
Abstract Classes
17
Shape
Circle Rectangle
Abstract Classes
 Abstract class can NOT be instantiated
 An abstract class may or may not include abstract
methods
 If it has at least one abstract method, it must be
declared abstract
 To use an abstract class, you need to inherit it
18
public abstract class Shape {}
public class Circle extends Shape {}
Shape shape = new Shape(); // Compile time error
Shape circle = new Circle(); // polymorphism
Problem: Shapes
19
Shape
-Double perimeter
-Double area
+getPerimeter()
#setPerimeter(Double perimeter)
+calculatePerimeter
+calculateArea
Rectangle
-Double height
-Double width
+calculatePerimeter
+calculateArea
Circle
-Double radius
+calculatePerimeter
+calculateArea
Encapsulate
area
Solution: Shapes
20
public abstract class Shape {
private Double perimeter;
private Double area;
protected void setPerimeter(Double perimeter) {
this.perimeter = perimeter;
}
public Double getPerimeter() { return this.perimeter; }
protected void setArea(Double area) {this.area = area; }
public Double getArea() { return this.area; }
protected abstract void calculatePerimeter();
protected abstract void calculateArea();
}
Solution: Shapes
21
public class Rectangle extends Shape {
//TODO: Add fields
public Rectangle(Double height, Double width) {
this.setHeight(height); this.setWidth(width);
this.calculatePerimeter(); this.calculateArea(); }
//TODO: Add getters and setters
@Override
protected void calculatePerimeter() {
setPerimeter(this.height * 2 + this.width * 2); }
@Override
protected void calculateArea() {
setArea(this.height * this.width); } }
Solution: Shapes
22
public class Circle extends Shape {
private Double radius;
public Circle (Double radius) {
this.setRadius(radius);
this.calculatePerimeter();
this.calculateArea();
}
public final Double getRadius() {
return radius;
}
//TODO: Finish encapsulation
//TODO: Override calculate Area and Perimeter
}
 …
 …
 …
Summary
23
 Polymorphism - Definition and Types
 Override Methods
 Overload Methods
 Abstraction
 Classes
 Methods
 https://softuni.bg/modules/59/java-advanced
SoftUni Diamond Partners
SoftUni Organizational Partners
 Software University – High-Quality Education and
Employment Opportunities
 softuni.bg
 Software University Foundation
 http://softuni.foundation/
 Software University @ Facebook
 facebook.com/SoftwareUniversity
 Software University Forums
 forum.softuni.bg
Trainings @ Software University (SoftUni)
 This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-
NonCommercial-ShareAlike 4.0 International" license
License
28

20.5 Java polymorphism

  • 1.
    Abstract Classes, AbstractMethods, Override Methods Polymorphism Software University http://softuni.bg SoftUni Team Technical Trainers
  • 2.
    1. Polymorphism  Whatis Polymorphism?  Types of Polymorphism  Override Methods  Overload Methods 2. Abstract Classes  Abstract Methods Table of Contents 2
  • 3.
  • 4.
  • 5.
     From theGreek  Such as a word having several different meanings based on the context  Often referred to as the third pillar of OOP, after encapsulation and inheritance What is Polymorphism? 5 Polys (many) Morphe (shape/forms) Polymorphos
  • 6.
     Ability ofan object to take on many forms Polymorphism in OOP 6 public interface Animal {} public abstract class Mammal {} public class Person extends Mammal implements Animal {} Person IS-A Person Person IS-A Mammal Person IS-AN Object Person IS-AN Animal
  • 7.
     Variables aresaved in reference type  You can use only reference methods  If you need object method you need to cast it or override it Reference Type and Object Type 7 public class Person extends Mammal implements Animal {} Animal person = new Person(); Mammal personOne = new Person(); Person personTwo = new Person(); Reference Type Object Type
  • 8.
     Check ifobject is an instance of a specific class if (peter.getClass() == Person.class) { ((Person) peter).getSalary(); } Keyword - instanceof 8 Mammal george = new Person(); Person peter = new Person(); Cast to object type and use its methods if (george instanceof Person) { ((Person) george).getSalary(); } Check object type of person
  • 9.
     Runtime polymorphism Compile time polymorphism Types of Polymorphism 9 public class Shape {} public class Circle extends Shape {} public static void main(String[] args) { Shape shape = new Circle(); } int sum(int a, int b, int c){} double sum(Double a, Double b){} Method overloading Method overriding
  • 10.
     Also knownas Static Polymorphism  Argument lists could differ in  Number of parameters  Data type of parameters  Sequence of Data type of parameters Compile Time Polymorphism 10 static int myMethod(int a, int b) {} static Double myMethod(Double a, Double b) {} Method overloading
  • 11.
     Create aclass MathOperation, which should have method add()  Must be invoked with two, three or four integers Problem: MathOperation 11 MathOperation +add(int a, int b): int +add(int a, int b, int c): int +add(int a, int b, int c, int d): int Check your solution here :https://judge.softuni.bg/Contests/1592/Polymorphism-Lab
  • 12.
    Solution: Math Operation 12 publicclass MathOperation { public int add(int a, int b) { return a + b; } public int add(int a, int b, int c) { return a + b + c; } public int add(int a, int b, int c, int d) { return a + b + c + d; } }
  • 13.
     Overloading cantake place in the same class or in its sub-class  Constructors in Java can be overloaded  Overloaded methods must have a different argument list  Overloaded method should always be the part of the same class (can also take place in sub class), with same name but different parameters  They may have the same or different return types Rules for Overloading Method 13
  • 14.
     Using ofoverride method Runtime Polymorphism 14 public static void main(String[] args) { Rectangle rect = new Rectangle(3.0, 4.0); Rectangle square = new Square(4.0); System.out.println(rect.area()); System.out.println(square.area()); } Method overriding
  • 15.
     Also knownas Dynamic Polymorphism Runtime Polymorphism 15 public class Square extends Rectangle { @Override public Double area() { return this.a * this.a; } } Method overriding public class Rectangle { public Double area() { return this.a * this.b; } }
  • 16.
     Overriding cantake place in sub-class  Argument list must be the same as that of the parent method  The overriding method must have same return type  Access modifier cannot be more restrictive  Private, static and final methods can NOT be overriden  The overriding method must not throw new or broader checked exceptions Rules for Overriding Method 16
  • 17.
  • 18.
    Abstract Classes  Abstractclass can NOT be instantiated  An abstract class may or may not include abstract methods  If it has at least one abstract method, it must be declared abstract  To use an abstract class, you need to inherit it 18 public abstract class Shape {} public class Circle extends Shape {} Shape shape = new Shape(); // Compile time error Shape circle = new Circle(); // polymorphism
  • 19.
    Problem: Shapes 19 Shape -Double perimeter -Doublearea +getPerimeter() #setPerimeter(Double perimeter) +calculatePerimeter +calculateArea Rectangle -Double height -Double width +calculatePerimeter +calculateArea Circle -Double radius +calculatePerimeter +calculateArea Encapsulate area
  • 20.
    Solution: Shapes 20 public abstractclass Shape { private Double perimeter; private Double area; protected void setPerimeter(Double perimeter) { this.perimeter = perimeter; } public Double getPerimeter() { return this.perimeter; } protected void setArea(Double area) {this.area = area; } public Double getArea() { return this.area; } protected abstract void calculatePerimeter(); protected abstract void calculateArea(); }
  • 21.
    Solution: Shapes 21 public classRectangle extends Shape { //TODO: Add fields public Rectangle(Double height, Double width) { this.setHeight(height); this.setWidth(width); this.calculatePerimeter(); this.calculateArea(); } //TODO: Add getters and setters @Override protected void calculatePerimeter() { setPerimeter(this.height * 2 + this.width * 2); } @Override protected void calculateArea() { setArea(this.height * this.width); } }
  • 22.
    Solution: Shapes 22 public classCircle extends Shape { private Double radius; public Circle (Double radius) { this.setRadius(radius); this.calculatePerimeter(); this.calculateArea(); } public final Double getRadius() { return radius; } //TODO: Finish encapsulation //TODO: Override calculate Area and Perimeter }
  • 23.
     …  … … Summary 23  Polymorphism - Definition and Types  Override Methods  Overload Methods  Abstraction  Classes  Methods
  • 24.
  • 25.
  • 26.
  • 27.
     Software University– High-Quality Education and Employment Opportunities  softuni.bg  Software University Foundation  http://softuni.foundation/  Software University @ Facebook  facebook.com/SoftwareUniversity  Software University Forums  forum.softuni.bg Trainings @ Software University (SoftUni)
  • 28.
     This course(slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license License 28

Editor's Notes

  • #3 (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #6 Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.
  • #12 11##
  • #13 12##
  • #14 To pass more specific object to method
  • #16 Demo (look at View -> Notes Page)
  • #17 To pass more specific object to method
  • #20 19##
  • #21 20##
  • #22 21##
  • #23 22##