Interfaces vs Abstract Classes
Abstraction vs Encapsulation
Interfaces and Abstraction
Software University
http://softuni.bg
SoftUni Team
http://softuni.bg
1. Abstraction
ď‚§ Abstraction vs Encapsulation
2. Interfaces
ď‚§ Default Methods
ď‚§ Static Methods
3. Abstract Classes
4. Interfaces vs Abstract Classes
Table of Contents
2
sli.do
#java-advanced
Have a Question?
Working with Abstraction
Abstraction
ď‚§ Latin origin
ď‚§ Preserving information that is relevant in a context
ď‚§ Forgetting information that is irrelevant in that
context
What is Abstraction?
5
Abs
(away from)
Trahere
(to draw)
Abstraction
ď‚§ Abstraction means ignoring irrelevant features, properties, or
functions and emphasizing the relevant ones …
ď‚§ ... relevant to the context of the project we develop
ď‚§ Abstraction helps managing complexity
ď‚§ Abstraction lets you focus on what the object does instead of
how it does it
Abstraction in OOP
6
"Relevant" to
what?
ď‚§ There are 2 ways to achieve abstraction in Java
ď‚§ Interfaces (100% abstraction)
ď‚§ Abstract class (0% - 100% abstraction)
Achieving Abstraction
7
public interface Animal {}
public abstract class Mammal {}
public class Person extends Mammal implements Animal {}
Abstraction vs. Encapsulation
ď‚§ Abstraction
ď‚§ Process of hiding the
implementation details
and showing only
functionality to the user
ď‚§ Achieved with interfaces
and abstract classes
ď‚§ Encapsulation
ď‚§ Used to hide the code
and data inside a single
unit to protect the data
from the outside world
ď‚§ Achieved with access
modifiers (private,
protected, public)
8
Interfaces
Working with Interfaces
ď‚§ Internal addition by compiler
Interface
10
public interface Printable {
int MIN = 5;
void print();
}
interface Printable {
public static final int MIN = 5;
public abstract void print();
}
compiler
"public abstract"
before methods
"public static final"
before fields
Public or default
modifier
Keyword
Name
ď‚§ Relationship between classes and interfaces
ď‚§ Multiple inheritance
implements vs extends
11
Interface
implementsextends extends
Interface
Interface
ClassClass
Class
Class
InterfaceInterface Interface Interface
Interface
extendsimplements
ď‚§ Implementation of print() is provided in class Document
Interface Example
12
public interface Printable {
void print();
}
class Document implements Printable {
public void print() { System.out.println("Hello"); }
public static void main(String args[]) {
Printable doc = new Document();
doc.print(); // Hello
}
}
Polymorphism
Problem: Car Shop
13
Seat
-countryProduced: String
+toString(): String<<interface>>
<<Car>>
+TIRES: Integer
+getModel(): String
+getColor(): String
+getHorsePower(): Integer
Serializable
Check your solution here :https://judge.softuni.bg/Contests/1581/Interfaces-and-Abstraction-Lab
Solution: Car Shop (1)
14
public interface Car {
int TIRES = 4;
String getModel();
String getColor();
Integer getHorsePower();
String countryProduced();
}
Solution: Car Shop (2)
15
public class Seat implements Car, Serializable {
// TODO: Add fields, constructor and private methods
@Override
public String getModel() { return this.model; }
@Override
public String getColor() { return this.color; }
@Override
public Integer getHorsePower() { return this.horsePower; }
}
ď‚§ Interface can extend another interface
Extend Interface
16
public interface Showable {
void show();
}
public interface Printable extends Showable {
void print();
}
ď‚§ Class which implements child interface must provide
implementation for parent interface too
Extend Interface
17
class Circle implements Printable
public void print() {
System.out.println("Hello");
}
public void show() {
System.out.println("Welcome");
}
ď‚§ Refactor your first problem code
ď‚§ Add for rentable cars
ď‚§ Add class Cinterface for sellable cars
ď‚§ Add interface arImpl
ď‚§ Add class Audi, which extends CarImpl and implements
rentable
ď‚§ Refactor class Seat to extends CarImpl and implements rentable
Problem: Car Shop Extended
18
Solution: Car Shop Extended (1)
19
public interface Sellable extends Car {
Double getPrice();
}
public interface Rentable extends Car {
Integer getMinRentDay();
Double getPricePerDay();
}
Solution: Car Shop Extended (2)
20
public class Audi extends CarImpl implements Rentable {
public Integer getMinRentDay() {
return this.minDaysForRent; }
public Double getPricePerDay() {
return this.pricePerDay; }
// TODO: Add fields, toString() and Constructor
}
ď‚§ Since Java 8 we can have method body in the interface
ď‚§ If you need to override default method think about your design
Default Method
21
public interface Drawable {
void draw();
default void msg() {
System.out.println("default method:");
}
}
ď‚§ Implementation is not needed for default methods
Default Method
22
class TestInterfaceDefault {
public static void main(String args[]) {
Drawable d = new Rectangle();
d.draw(); // drawing rectangle
d.msg(); // default method
}
}
ď‚§ Since Java 11, we can have static method in interface
Static Method
23
public interface Drawable {
void draw();
static int cube(int x) { return x*x*x; }
}
public static void main(String args[]) {
Drawable d = new Rectangle();
d.draw();
System.out.println(Drawable.cube(3)); } // 27
ď‚§ Design a project, which has
ď‚§ Interface for Person
ď‚§ 3 implementations
for different nationalities
ď‚§ Override where needed
Problem: Say Hello
24
<<Person>>
European
-name: String
<<interface>>
<<Person>>
+getName(): String
+sayHello():String
<<Person>>
Bulgarian
-name: String
+sayHello(): String
<<Person>>
Chinese
-name: String
+sayHello(): String
Solution: Say Hello (1)
25
public interface Person {
String getName();
default String sayHello() { return "Hello"; }
}
public class European implements Person {
private String name;
public European(String name) { this.name = name; }
public String getName() { return this.name; }
}
Solution: Say Hello (2)
26
public class Bulgarian implements Person {
private String name;
public Bulgarian(String name) {
this.name = name;
}
public String getName() { return this.name; }
public String sayHello() { return "Здравей"; }
}
// TODO: implement class Chinese
Abstract Classes
Abstract Classes and Methods
27
ď‚§ Cannot be instantiated
ď‚§ May contain abstract methods
ď‚§ Must provide implementation for all inherited
interface members
ď‚§ Implementing an interface might map the interface
methods onto abstract methods
Abstract Class
28
public abstract class Animal {
}
Abstract Methods
ď‚§ Declarations are only permitted in abstract classes
ď‚§ Bodies must be empty (no curly braces)
ď‚§ An abstract method declaration provides no actual
implementation:
29
public abstract void build();
Interfaces vs Abstract Classes
30
Interface vs Abstract Class (1)
ď‚§ Interface
ď‚§ A class may implement
several interfaces
ď‚§ Cannot have access
modifiers, everything is
assumed as public
ď‚§ Abstract Class (AC)
ď‚§ May inherit only
one abstract class
ď‚§ Provides implementation
and/or just the signature
that has to be overridden
ď‚§ Can contain access
modifiers for the fields,
functions, properties
31
Interface vs Abstract Class (2)
ď‚§ Interface
ď‚§ If we add a new method
we must track down
all the implementations of
the interface and
define implementation
for the new method
ď‚§ Abstract Class
ď‚§ Fields and constants
can be defined
ď‚§ If we add a new method
we have the option of
providing default
implementation
32
ď‚§ Refactor the code from the last problem
ď‚§ Add BasePerson abstract class
ď‚§ In which move all code duplication from European, Bulgarian,
Chinese
Problem: Say Hello Extended
33
BasePerson
#BasePerson(name)
-name: String
-setName(): void
Solution: Say Hello Extended
34
public abstract class BasePerson implements Person {
private String name;
protected BasePerson(String name) {
this.setName(name);
}
private void setName(String name) { this.name = name; }
@Override
public String getName() {
return this.name;
}
}
 …
 …
 …
Summary
35
 Abstraction – hiding implementation and
showing functionality
ď‚§ Interfaces
ď‚§ implements vs extends
ď‚§ Default and Static methods
ď‚§ Abstract classes
ď‚§ Interfaces vs Abstract Classes
ď‚§ 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
40

20.4 Java interfaces and abstraction

  • 1.
    Interfaces vs AbstractClasses Abstraction vs Encapsulation Interfaces and Abstraction Software University http://softuni.bg SoftUni Team http://softuni.bg
  • 2.
    1. Abstraction ď‚§ Abstractionvs Encapsulation 2. Interfaces ď‚§ Default Methods ď‚§ Static Methods 3. Abstract Classes 4. Interfaces vs Abstract Classes Table of Contents 2
  • 3.
  • 4.
  • 5.
    ď‚§ Latin origin ď‚§Preserving information that is relevant in a context ď‚§ Forgetting information that is irrelevant in that context What is Abstraction? 5 Abs (away from) Trahere (to draw) Abstraction
  • 6.
     Abstraction meansignoring irrelevant features, properties, or functions and emphasizing the relevant ones …  ... relevant to the context of the project we develop  Abstraction helps managing complexity  Abstraction lets you focus on what the object does instead of how it does it Abstraction in OOP 6 "Relevant" to what?
  • 7.
    ď‚§ There are2 ways to achieve abstraction in Java ď‚§ Interfaces (100% abstraction) ď‚§ Abstract class (0% - 100% abstraction) Achieving Abstraction 7 public interface Animal {} public abstract class Mammal {} public class Person extends Mammal implements Animal {}
  • 8.
    Abstraction vs. Encapsulation ď‚§Abstraction ď‚§ Process of hiding the implementation details and showing only functionality to the user ď‚§ Achieved with interfaces and abstract classes ď‚§ Encapsulation ď‚§ Used to hide the code and data inside a single unit to protect the data from the outside world ď‚§ Achieved with access modifiers (private, protected, public) 8
  • 9.
  • 10.
    ď‚§ Internal additionby compiler Interface 10 public interface Printable { int MIN = 5; void print(); } interface Printable { public static final int MIN = 5; public abstract void print(); } compiler "public abstract" before methods "public static final" before fields Public or default modifier Keyword Name
  • 11.
    ď‚§ Relationship betweenclasses and interfaces ď‚§ Multiple inheritance implements vs extends 11 Interface implementsextends extends Interface Interface ClassClass Class Class InterfaceInterface Interface Interface Interface extendsimplements
  • 12.
    ď‚§ Implementation ofprint() is provided in class Document Interface Example 12 public interface Printable { void print(); } class Document implements Printable { public void print() { System.out.println("Hello"); } public static void main(String args[]) { Printable doc = new Document(); doc.print(); // Hello } } Polymorphism
  • 13.
    Problem: Car Shop 13 Seat -countryProduced:String +toString(): String<<interface>> <<Car>> +TIRES: Integer +getModel(): String +getColor(): String +getHorsePower(): Integer Serializable Check your solution here :https://judge.softuni.bg/Contests/1581/Interfaces-and-Abstraction-Lab
  • 14.
    Solution: Car Shop(1) 14 public interface Car { int TIRES = 4; String getModel(); String getColor(); Integer getHorsePower(); String countryProduced(); }
  • 15.
    Solution: Car Shop(2) 15 public class Seat implements Car, Serializable { // TODO: Add fields, constructor and private methods @Override public String getModel() { return this.model; } @Override public String getColor() { return this.color; } @Override public Integer getHorsePower() { return this.horsePower; } }
  • 16.
    ď‚§ Interface canextend another interface Extend Interface 16 public interface Showable { void show(); } public interface Printable extends Showable { void print(); }
  • 17.
    ď‚§ Class whichimplements child interface must provide implementation for parent interface too Extend Interface 17 class Circle implements Printable public void print() { System.out.println("Hello"); } public void show() { System.out.println("Welcome"); }
  • 18.
    ď‚§ Refactor yourfirst problem code ď‚§ Add for rentable cars ď‚§ Add class Cinterface for sellable cars ď‚§ Add interface arImpl ď‚§ Add class Audi, which extends CarImpl and implements rentable ď‚§ Refactor class Seat to extends CarImpl and implements rentable Problem: Car Shop Extended 18
  • 19.
    Solution: Car ShopExtended (1) 19 public interface Sellable extends Car { Double getPrice(); } public interface Rentable extends Car { Integer getMinRentDay(); Double getPricePerDay(); }
  • 20.
    Solution: Car ShopExtended (2) 20 public class Audi extends CarImpl implements Rentable { public Integer getMinRentDay() { return this.minDaysForRent; } public Double getPricePerDay() { return this.pricePerDay; } // TODO: Add fields, toString() and Constructor }
  • 21.
    ď‚§ Since Java8 we can have method body in the interface ď‚§ If you need to override default method think about your design Default Method 21 public interface Drawable { void draw(); default void msg() { System.out.println("default method:"); } }
  • 22.
    ď‚§ Implementation isnot needed for default methods Default Method 22 class TestInterfaceDefault { public static void main(String args[]) { Drawable d = new Rectangle(); d.draw(); // drawing rectangle d.msg(); // default method } }
  • 23.
    ď‚§ Since Java11, we can have static method in interface Static Method 23 public interface Drawable { void draw(); static int cube(int x) { return x*x*x; } } public static void main(String args[]) { Drawable d = new Rectangle(); d.draw(); System.out.println(Drawable.cube(3)); } // 27
  • 24.
    ď‚§ Design aproject, which has ď‚§ Interface for Person ď‚§ 3 implementations for different nationalities ď‚§ Override where needed Problem: Say Hello 24 <<Person>> European -name: String <<interface>> <<Person>> +getName(): String +sayHello():String <<Person>> Bulgarian -name: String +sayHello(): String <<Person>> Chinese -name: String +sayHello(): String
  • 25.
    Solution: Say Hello(1) 25 public interface Person { String getName(); default String sayHello() { return "Hello"; } } public class European implements Person { private String name; public European(String name) { this.name = name; } public String getName() { return this.name; } }
  • 26.
    Solution: Say Hello(2) 26 public class Bulgarian implements Person { private String name; public Bulgarian(String name) { this.name = name; } public String getName() { return this.name; } public String sayHello() { return "Здравей"; } } // TODO: implement class Chinese
  • 27.
  • 28.
    ď‚§ Cannot beinstantiated ď‚§ May contain abstract methods ď‚§ Must provide implementation for all inherited interface members ď‚§ Implementing an interface might map the interface methods onto abstract methods Abstract Class 28 public abstract class Animal { }
  • 29.
    Abstract Methods ď‚§ Declarationsare only permitted in abstract classes ď‚§ Bodies must be empty (no curly braces) ď‚§ An abstract method declaration provides no actual implementation: 29 public abstract void build();
  • 30.
  • 31.
    Interface vs AbstractClass (1) ď‚§ Interface ď‚§ A class may implement several interfaces ď‚§ Cannot have access modifiers, everything is assumed as public ď‚§ Abstract Class (AC) ď‚§ May inherit only one abstract class ď‚§ Provides implementation and/or just the signature that has to be overridden ď‚§ Can contain access modifiers for the fields, functions, properties 31
  • 32.
    Interface vs AbstractClass (2) ď‚§ Interface ď‚§ If we add a new method we must track down all the implementations of the interface and define implementation for the new method ď‚§ Abstract Class ď‚§ Fields and constants can be defined ď‚§ If we add a new method we have the option of providing default implementation 32
  • 33.
    ď‚§ Refactor thecode from the last problem ď‚§ Add BasePerson abstract class ď‚§ In which move all code duplication from European, Bulgarian, Chinese Problem: Say Hello Extended 33 BasePerson #BasePerson(name) -name: String -setName(): void
  • 34.
    Solution: Say HelloExtended 34 public abstract class BasePerson implements Person { private String name; protected BasePerson(String name) { this.setName(name); } private void setName(String name) { this.name = name; } @Override public String getName() { return this.name; } }
  • 35.
     …  … … Summary 35  Abstraction – hiding implementation and showing functionality  Interfaces  implements vs extends  Default and Static methods  Abstract classes  Interfaces vs Abstract Classes
  • 36.
  • 37.
  • 38.
  • 39.
     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)
  • 40.
    ď‚§ This course(slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license License 40

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.*
  • #8 There are two ways to achieve abstraction - Using Abstract Classes - Using Interfaces
  • #11 There are two ways to achieve abstraction - Using Abstract Classes - Using Interfaces
  • #12 There are two ways to achieve abstraction - Using Abstract Classes - Using Interfaces
  • #13 There are two ways to achieve abstraction - Using Abstract Classes - Using Interfaces
  • #14 There are two ways to achieve abstraction - Using Abstract Classes - Using Interfaces
  • #15 There are two ways to achieve abstraction - Using Abstract Classes - Using Interfaces
  • #16 There are two ways to achieve abstraction - Using Abstract Classes - Using Interfaces
  • #17 There are two ways to achieve abstraction - Using Abstract Classes - Using Interfaces
  • #18 There are two ways to achieve abstraction - Using Abstract Classes - Using Interfaces
  • #19 There are two ways to achieve abstraction - Using Abstract Classes - Using Interfaces
  • #20 There are two ways to achieve abstraction - Using Abstract Classes - Using Interfaces
  • #21 There are two ways to achieve abstraction - Using Abstract Classes - Using Interfaces
  • #22 There are two ways to achieve abstraction - Using Abstract Classes - Using Interfaces
  • #23 There are two ways to achieve abstraction - Using Abstract Classes - Using Interfaces
  • #24 There are two ways to achieve abstraction - Using Abstract Classes - Using Interfaces
  • #25 There are two ways to achieve abstraction - Using Abstract Classes - Using Interfaces
  • #26 There are two ways to achieve abstraction - Using Abstract Classes - Using Interfaces
  • #27 There are two ways to achieve abstraction - Using Abstract Classes - Using Interfaces
  • #29 There are two ways to achieve abstraction - Using Abstract Classes - Using Interfaces
  • #34 Java interfaces are like purely abstract classes, but: - All interface methods are abstract - Interface members do not have scope modifiers - Their scope is assumed public - But public is not specified explicitly - Cannot define fields, inner types and constructors
  • #35 There are two ways to achieve abstraction - Using Abstract Classes - Using Interfaces