You are on page 1of 27

Chapter 13 (Part 2)

Abstraction, Encapsulation and


Interface
Outlines

• Abstraction
• Encapsulation
• Interface
Abstraction
•  Abstraction is one of the core principles of Object-oriented programming practices.

• Abstraction is a process of hiding the implementation details and showing only functionality to the user.

• In Java, abstraction is achieved using abstract classes and interfaces.

• Real-life example of abstraction which can be a TV remote.

• Abstract class: is a restricted class that cannot be used to create objects.

• Abstract method: can only be used in an abstract class, and it does not have a body. The body is
provided by the subclass (inherited from).

• An abstract class can have both abstract and regular methods:

• To access the abstract class, it must be inherited from another class.


Abstract class syntax
abstract class ClassName
{
...

abstract returnType Metho1( ); // abstract method
abstract protected or public returnType Metho1( ); // abstract method

……
Type Method2() // regular method
{
// method body
}
}

• When a class contains one or more abstract methods, it should be declared as abstract class.
• We cannot declare abstract constructors or abstract static methods.
Abstract classes and methods
• Abstract methods have abstract in the signature.
• Abstract methods have no body.
• Abstract methods can’t be private.
• Abstract methods make the class abstract
• Concrete subclasses complete the implementation.
• It can have constructors and static methods also.
• A concrete subclass must implement all abstract methods of its superclass
• Any subclass of an abstract class must either implement all the abstract methods in the
superclass or be itself declared abstract.
• BUT – each concrete subclass (A class which is not abstract is referred) can implement the
method differently
Example
class Cat2 extends Animal1 {
abstract class Animal1 { void speak() {
abstract void speak(); System.out.println("Cat is speaking: Meow Meow
void sleep() { ");
System.out.println("Animals are sleeping"); } }
} public class AbstractionExample {
} public static void main(String[] args) {
class Dog extends Animal1 { Animal1 dog=new Dog();
void speak() { Animal1 cat=new Cat2();
System.out.println("Dog is speaking : Woof Woof"); Animal1 animal[]=new Animal1[2];
} animal[0]=dog; animal[1]=cat;
} for( Animal1 a: animal)
{ a.speak();a.sleep(); } } }
Abstract Class Example

• Shape is a abstract class.


• Circle and Rectangle are concrete class.
• Find area and p
Shape

Circle Rectangle
Stopping Overriding with final
• to prevent method overriding from super class, you can mark that method as final,
and no one can override it then
class Animal {
final void breathe() { System.out.println("Breathing"); }
}
class Fish extends Animal {
public void breathe() { System.out.println("Bubbling"); }
}
public class App {
public static void main(String[] args) {
System.out.println("Creating an animal...");
Animal a = new Animal(); a.breathe();
System.out.println("Creating a lungfish...");
Fish f = new Fish(); f.breathe(); }
}
Stopping Inheritance with final
• You can prevent a class from being subclassed by declaring the
entire class final.
final class Animal {
public void breathe() { System.out.println("Breathing"); }
}
class Fish extends Animal {
public void breathe() { System.out.println("Bubbling"); }
}
public class App {
public static void main(String[] args) {
System.out.println("Creating an animal...");
Animal a = new Animal(); a.breathe();
System.out.println();
System.out.println("Creating a lungfish...");
Fish f = new Fish(); f.breathe(); }
}
Creating Constants with final

• There’s another use for final in Java—you can use it to declare


constants.

public class App {


public static void main(String[] args)
{
final int a = 5; a = 6;
}
}
Interface
• The interface in java is a mechanism to achieve abstraction.

• There can be only abstract methods in the java interface not method body.

• It is used to achieve abstraction and multiple inheritance in Java.

• It cannot be instantiated just like abstract class.

• It has no constructor – no instances of an interface

• It has static and final (not instance) constants and abstract methods.

• A Java interface is a collection of constants and abstract methods

• since all methods in an interface are abstract, the abstract modifier is usually left off
interface Name {

// constant definitions
// method definitions
}
Understanding relationship between classes and interfaces
Example

interface printable { public class Interface {


int num = 5;
void print(); public static void main(String[] args) {
} MyClass1 myobj = new MyClass1();
class MyClass1 implements printable { System.out.println(myobj.num);
public void print() { myobj.print();
System.out.println("Hello"); }
} }
}
Multiple inheritance in Java by interface.

If a class implements multiple interfaces, or an interface extends


multiple interfaces i.e. known as multiple inheritance.
Example
interface suminterface {
int sum(int a, int b);
} public class MultInheritanceByInterface {
interface mulinterface { public static void main(String[] args) {
int mult(int a, int b); Calculator c = new Calculator();
} System.out.println(c.sum(1, 2));
class Calculator implements suminterface, System.out.println(c.mult(2, 3));
mulinterface {
}
public int mult(int a, int b) {
// TODO Auto-generated method stub
}

return a * b;
}
public int sum(int a, int b) {
// TODO Auto-generated method stub
return a + b;
Multiple inheritance is not supported through class in java but it is possible by
interface

• Multiple inheritance is not supported in case of class because of ambiguity. But it


is supported in case of interface because there is no ambiguity as implementation
is provided by the implementation class.
Example

interface firstinterface {
void message(); public class Main {
} public static void main(String[] args) {
interface secondinterface { MyClass2 obj = new MyClass2();
void message(); obj.message();
} }
class MyClass2 implements firstinterface, }
secondinterface {
public void message() {
System.out.println("Own implementation in
Class ");
}
}
Interface Inheritance
interface Vehicles {
void hasWheels();
} public class InterfaceInheritance {
interface Car extends Vehicles { public static void main(String[] args) {
void hasSeat(); MyCar mycar = new MyCar();
} mycar.hasSeat();
class MyCar implements Car { mycar.hasWheels();
public void hasWheels() { }
System.out.println("4 Wheels"); }
}
public void hasSeat() {
System.out.println("4 Seats ");
}
}
Java 8 Default Method in Interface

• Java 8, we can have method body in interface. But we need to make it default method.

• We can provide default implementation and the implementation classes can chose
which one to override.

• Can also have static method in interface.

• InterfaceDefault.java
Default and Static Method in interface
interface Drawable {
void draw();
default void print() { public class DefaultStaticInterface {
System.out.println("Printing Rectangle"); public static void main(String[] args) {
} Rectagle r1=new Rectagle();
static int findarea(int width, int height) { r1.draw();
return width* height; r1.print();
} System.out.println(Drawable.findarea(2,
} 3));
class Rectagle implements Drawable { }
public void draw() {
System.out.println("Drawing Rectangle "); }
}
}
Question (1)

• The given program ,class named AB has two parent classs (class A and class B).
But Java does not support multiple inheritances in classes because of “Diamond
problem”. However multiple inheritances are supported in interface. How to fix
the error and rewrite to get multiple inheritance for the given problem.
class A {
public void getA() {
System.out.println("Printing A.....");
}}
class B {
public void getB() {
System.out.println("Printing B.....");
}}
public class AB extends A,B
{
public static void main(String[] args) {
AB ab=new AB();
ab.getA(); ab.getB();
}}
Question (2)

• The given program ,class named CalendarClock has two parent classs (class
Calendar and class Clock). But Java does not support multiple inheritances in
classes because of “Diamond problem”. However multiple inheritances are
supported in interface. How to fix the error and rewrite to get multiple inheritance
for the given problem.
import java.time.*;
class Calendar {
public void getLocalDate()
{
System.out.println("Current Date "+LocalDate.now());
}
}
class Clock {
public void getLocalTime()
{
System.out.println("Current Clock "+LocalTime.now());
}
}
public class CalenderClock implements Calendar, Clock {

public static void main(String[] args) {


CalenderClock cc = new CalenderClock();
cc.getLocalDate();
cc.getLocalTime();
}
}
Encapsulation

• The whole idea behind encapsulation is to hide the implementation details from users. If a
data member is private it means it can only be accessed within the same class. No outside
class can access private data member (variable) of other class.
• How to implement encapsulation in java:
1) Make the instance variables private so that they cannot be accessed directly from
outside the class. You can only set and get values of these variables through the methods
of the class.
2) Have getter and setter methods in the class to set and get the values of the fields.
• By providing only a setter or getter method, you can make the class read-only or write-
only
Example
class Student
{
private String name; public class StudentMain {
private String address;
public String getName() { public static void main(String[] args) {
return name; Student s=new Student();
} s.setName("su su");
public void setName(String name) { s.setAddress("Yangon");
this.name = name; System.out.println(s.getName());
} System.out.println(s.getAddress());

public String getAddress() {


return address;
}
}
public void setAddress(String address) {
}
this.address = address;
}

You might also like