Object Oriented Programming
Chapter - 5
Abstraction
Compiled By Yohans Samuel(MSc)
1
Contents
ABSTRACTION
1. Abstract Class
2. Abstract Methods
3. Interface
4. Interface [Java 8]
5. Inner and Outer Classes
6. Packages
2
Abstraction (1)
• Abstraction is the quality of dealing with ideas
rather than events.
• In object oriented programming,
– abstraction is a process of hiding the
implementation details from the user, only the
functionality will be provided to the user.
• In other words, user will have the information
on what the object does instead of how it does.
3
Abstraction (2)
• In Java, Abstraction is achieved using Abstract classes,
Abstract methods and Interfaces.
• The abstract keyword is a non-access modifier, used for classes
and methods:
– Abstract class: is a restricted class that cannot be used to
create objects (to access it, it must be inherited from another
class).
– 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).
4
Abstraction (3)
• Abstraction lets you focus on what the object does
instead of how it does it.
Ways to achieve Abstraction
• There are two ways to achieve abstraction in java
– Abstract class (0 to 100%)
– Interface (100%)
5
Abstract Class (1)
• A class which contains the abstract keyword in its declaration is known
as abstract class.
• Abstract classes may or may not contain abstract methods
– methods with out body ( public void get(); ) – only declaration of a method.
• But, if a class have at least one abstract method, then the class must
be declared as abstract.
• Abstract classes cannot be instantiated (cannot create object).
• If you inherit an abstract class you have to provide implementations to
all the abstract methods in it.
• Syntax:
<access specifier> abstract class <className> {
// code inside of the class }
• Example: public abstract class Shape { // code inside of the class }
6
Abstract Class (2)
• Suppose we were modeling the behavior of animals, by creating a class
hierarchy that started with a base class called Animal.
• Animals are capable of doing different things like flying, digging and
walking, but there are some common operations as well like eating and
sleeping.
• Some common operations are performed by all animals, but in a
different way as well.
• When an operation is performed in a different way, it is a good
candidate for an abstract method (forcing subclasses to provide a
custom implementation).
• Let's look at a very primitive Animal base class, which defines an
abstract method for making a sound (such as a dog barking, a cow
mooing etc.).
7
Abstract Class (3)
public abstract Class Animal { public class Cat extends Animal{
public void eat(String fd) { //implementation of abstract method
// do something void makeNoise(){
} System.out.print(“meow”);
public void sleep(int hours) { }}
// do something public class Dog extends Animal{
} //implementation of abstract method
// signature of abstract method void makeNoise(){
public abstract void System.out.print(“wuuwuu”);
makeNoise(); }
} }
8
Abstract Class (4)
• An abstract class can have both abstract and non-abstract
methods:
abstract class Animal {
public abstract void animalSound();
public void sleep() {
System.out.println("Zzz");
}
}
• From the above example, it is not possible to create an
object of the Animal class:
Animal myObj = new Animal(); // will generate an error
9
Abstract Class (5)
// Abstract class class Main {
abstract class Animal {
public static void main(String[] args) {
// Abstract method (does not have a body)
public abstract void animalSound();
// Create a Pig object
// Regular method Pig myPig = new Pig();
public void sleep() { myPig.animalSound();
System.out.println("Zzz");
myPig.sleep();
}
} }
// Subclass (inherit from Animal) }
class Pig extends Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
}
10
Abstract Class (6)
11
Abstract Methods (1)
• A method which is declared as abstract and does
not have implementation is known as an abstract
method.
• Example of abstract method
//no method body and abstract
abstract void printStatus();
12
Abstract Methods (2)
• The abstract Method is used for creating blueprints for classes or
interfaces.
• Here methods are defined but these methods don’t provide the
implementation.
• Abstract Methods can only be implemented using subclasses or
classes that implement the interfaces.
• These methods are sometimes referred to as subclasser responsibility
because they have no implementation specified in the super-class.
• Thus, a subclass must override them to provide a method definition.
13
Abstract Methods (3)
• A method that doesn't have its body is known as an abstract method.
We use the same abstract keyword to create abstract methods.
• For example, abstract void display(); Here, display() is an abstract
method.
• The body of display() is replaced by ;.
• If a class contains an abstract method, then the class should be declared
abstract. Otherwise, it will generate an error.
• For example,
// error
// class should be abstract
class Language {
// abstract method
abstract void method1();
} 14
Abstract Methods (4)
Important rules for abstract methods are mentioned below:
• Any class that contains one or more abstract methods must also be
declared abstract.
• If a class contains an abstract method it needs to be abstract and vice
versa is not true.
• If a non-abstract class extends an abstract class, then
– the class must implement all the abstract methods of the abstract class
– else the concrete class has to be declared as abstract as well.
• The following are various illegal combinations of other modifiers for
methods with respect to abstract modifiers:
final
abstract static
abstract private
15
Interface (1)
• Java Interface is an advanced level of achieving abstraction in the
Java Programming Language.
• Java Abstraction provides the functionality of a particular method by
hiding the implementation logic written inside the method.
• It helps in the reduction of complexity in the code and simplifies the
readability.
• Java interface is a reference type in Java, it is similar to class,
– it is a collection of abstract methods, static & final variables.
• Similar to Abstract Class, Java Interface is also a Class which
includes the Method Declaration but not its definition.
• A class implements an interface to inherit the abstract methods.
• Along with abstract methods, an interface can also include
constants, static methods, nested interfaces and default methods.
16
Interface (2)
• An interface is a completely "abstract class" that is used to group
related methods with empty bodies:
// interface
interface Animal {
// interface method (does not have a body)
public void animalSound();
// interface method (does not have a body)
public void run();
}
• To access the interface methods, the interface must be "implemented"
(kinda like inherited) by another class with the implements keyword
(instead of extends).
• The body of the interface method is provided by the "implementer"
class
17
Interface (3)
// Interface class Main {
interface Animal {
public static void main(String[] args)
public void animalSound();
{
public void sleep();
}
Pig myPig = new Pig();
// Pig "implements" the Animal interface // Create a Pig object
class Pig implements Animal { myPig.animalSound();
public void animalSound() { myPig.sleep();
// The body of animalSound() is provided here }
System.out.println("The pig says: wee wee");
}
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Zzz");
}
}
18
Interface (4)
Notes on Interfaces:
• Like abstract classes, interfaces cannot be used to create objects
(in the example above, it is not possible to create an "Animal"
object in the Main Class)
• Interface methods do not have a body - the body is provided by
the "implementer" class
• On implementation of an interface, you must override all of its
methods
• Interface methods are by default abstract and public.
• Interface attributes are by default public, static and final.
• An interface cannot contain a constructor (as it cannot be used to
create objects)
19
Interface (5)
Why And When To Use Interfaces?
• To achieve security - hide certain details and only show the
important details of an object (interface).
• Java does not support "multiple inheritance" (a class can only
inherit from one superclass).
• However, it can be achieved with interfaces, because the class
can implement multiple interfaces.
• Note: To implement multiple interfaces, separate them with a
comma (see example below).
20
Interface (6)
interface FirstInterface {
public void myMethod();
}
interface SecondInterface {
public void myOtherMethod();
}
class DemoClass implements FirstInterface, SecondInterface
{
public void myMethod() { class Main {
System.out.println("Some text.."); public static void main(String[] args) {
}
DemoClass myObj = new DemoClass();
public void myOtherMethod() {
myObj.myMethod();
System.out.println("Some other text...");
}
myObj.myOtherMethod();
} }
}
21
Interface (7)
• A class can extend another class similar to this an interface can
extend another interface.
• But only a class can extend to another interface, and vice-versa is
not allowed.
22
Interface (8)
• Although Class and Interface seem the same there have certain differences
between Classes and Interface.
• The major differences between a class and an interface are mentioned
below:
23
Interface in
Java 8 and later versions
24
Inner Classes (1)
• Inner class are defined inside the body of
another class known as outer class.
– can have access modifier or even can be marked as abstract
and final.
– have special relationship with outer class instances.
– This relationship allows them to have access to outer class
members including private members too.
25
Inner Classes (2)
An inner class is declared and coded inside the curly braces of outer
class.
• Inner class acts as a member of the outer class and can have any
access modifiers: abstract, final, public, protected, private, static.
• Inner class can access all members of the outer class including
those marked as private .
Instantiating an inner class
• To instantiate an instance of inner class, there should be a live
instance of outer class.
• An inner class instance can be created only from an outer class
instance.
• An inner class shares a special relationship with an instance of the
outer class.
26
Inner Classes (3)
class MyOuterClassDemo { public static void main(String args[]){
private int x= 1; MyOuterClassDemo outer = new
// inner class definition MyOuterClassDemo();
class MyInnerClassDemo { MyInnerClassDemo inner=outer.new
MyInnerClassDemo();
public void seeOuter () {
inner.seeOuter();
System.out.println("Outer Value of x
is :" + x); }
}
} // end inner class definition } // end outer class definition
27
Inner Classes (4)
• The public static void main code in the above example can be
replaced with this one.
• It will also give the same output.
public static void main(String args[]){
MyOuterClassDemo.MyInnerClassDemo inner = new
MyOuterClassDemo().new MyInnerClassDemo();
inner. seeOuter();
}
28
Packages (1)
• Sub-directories within which related classes can be placed
together for organization.
• Group of classes placed within folder(s).
• Example: package transportation can contain classes Airplane,
Train, Car, Boat, Bike
• To make a class a part of a package transportation we have to
write “package transportation” at the first line of code [you
cannot write any java code before package name]
• packages can have sub package.
• Example: java.awt [awt is a sub package in the java package]
29
Packages (2)
Importing a particular class
• Once declared that a class belongs to some package, the actual
name of the class is packageName.className
• Example: transportation.Car is the actual name for class Car
• To import anywhere in your code use: import transportation.Car
• if you need to use the class Car in other package, not in the same
package
Importing a package
• Importing a package means importing the whole classes of the
package.
Example: import java.awt.*;
• import java.awt.Graphics
• import java.awt.Button;
30
Packages (3)
• Classes in the same package can access each other without
importing
• You can avoid importing classes by using the filename of the
class [packageName.className] everywhere in code.
Drawbacks of importing the whole package
• causes the virtual machine to use extra RAM to keep track of
the names of the elements within that package
• Slows the system down slightly.
• Class collision can occur, if you have the same class name in
2 packages.
31
Packages (4)
Code organization with package
• packages are used to organize and group related classes
together.
• Java.io: contains classes for doing input/output
• Java.awt: contains classes for creating GUI
• Java.net: contains classes for doing network operations.
• Java.util: contains other tools for encoding decoding, vector,
stacks…
Implicit imports
• The classes of java.lang are automatically imported.
• Example: Math class and System class are directly used
without any import statements.
32
Questions?
33