Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
81 views

Java - Abstraction

The document discusses data abstraction and interfaces in Java. It defines data abstraction as hiding unnecessary details from users and exposing only essential information. Interfaces are used to achieve abstraction and loose coupling. An interface specifies what a class must do but not how. It defines a common behavior for classes to implement, allowing multiple inheritance of behaviors. The document provides examples of abstract classes, interfaces, and how to achieve multiple inheritance using interfaces in Java.

Uploaded by

Hari Krishnan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
81 views

Java - Abstraction

The document discusses data abstraction and interfaces in Java. It defines data abstraction as hiding unnecessary details from users and exposing only essential information. Interfaces are used to achieve abstraction and loose coupling. An interface specifies what a class must do but not how. It defines a common behavior for classes to implement, allowing multiple inheritance of behaviors. The document provides examples of abstract classes, interfaces, and how to achieve multiple inheritance using interfaces in Java.

Uploaded by

Hari Krishnan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Abstraction

Data Abstraction is the property by virtue of which only the essential details are displayed to
the user. The trivial or the non-essentials units are not displayed to the user. Ex: A car is
viewed as a car rather than its individual components.
Data Abstraction may also be defined as the process of identifying only the required
characteristics of an object ignoring the irrelevant details. The properties and behaviors of an
object differentiate it from other objects of similar type and also help in classifying/grouping
the objects.
Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerators will increase the speed of car or applying brakes will stop the car but he does not
know about how on pressing the accelerator the speed is actually increasing, he does not
know about the inner mechanism of the car or the implementation of accelerator, brakes etc
in the car. This is what abstraction is.
In java, abstraction is achieved by interfaces and abstract classes. We can achieve 100%
abstraction using interfaces.

Abstract classes and Abstract methods:


1. An abstract class is a class that is declared with abstract keyword.
2. An abstract method is a method that is declared without an implementation.
3. An abstract class may or may not have all abstract methods. Some of them can be
concrete methods
4. A method defined abstract must always be redefined in the subclass, thus
making overriding compulsory OR either make subclass itself abstract.
5. Any class that contains one or more abstract methods must also be declared with
abstract keyword.
6. There can be no object of an abstract class. That is, an abstract class cannot be directly
instantiated with the new operator.
7. An abstract class can have parametrized constructors and default constructor is always
present in an abstract class.

When to use abstract classes and abstract methods?

There are situations in which we want to define a superclass that declares the structure of a
given abstraction without providing a complete implementation of every method. That is,
sometimes we want to create a superclass that only defines a generalization form that will be
shared by all of its subclasses, leaving it to each subclass to fill in the details.
Consider a classic “shape” example, perhaps used in a computer-aided design system or game
simulation. The base type is “shape” and each shape has a color, size and so on. From this,
specific types of shapes are derived (inherited)-circle, square, triangle and so on – each of
which may have additional characteristics and behaviors. For example, certain shapes can be
flipped. Some behaviors may be different, such as calculation of area of a shape.
// Java program to illustrate the
// concept of Abstraction
abstract class Shape 
{
    String color;
      
    // these are abstract methods
    abstract double area();
    public abstract String toString();
      
    // abstract class can have constructor
    public Shape(String color) {
        System.out.println("Shape constructor called");
        this.color = color;
    }
      
    // this is a concrete method
    public String getColor() {
        return color;
    }
}
class Circle extends Shape
{
    double radius;
      
    public Circle(String color,double radius) {
  
        // calling Shape constructor
        super(color);
        System.out.println("Circle constructor called");
        this.radius = radius;
    }
  
    double area() {
        return Math.PI * Math.pow(radius, 2);
    }
  
    
    public String toString() {
        return "Circle color is " + super.color + 
                       "and area is : " + area();
    }
      
}
class Rectangle extends Shape{
  
    double length;
    double width;
      
    public Rectangle(String color,double length,double width) {
        // calling Shape constructor
        super(color);
        System.out.println("Rectangle constructor called");
        this.length = length;
        this.width = width;
    }
      
      double area() {
        return length*width;
    }
  
        public String toString() {
        return "Rectangle color is " + super.color + 
                           "and area is : " + area();
    }
  
}
public class Test 
{
    public static void main(String[] args)
    {
        Shape s1 = new Circle("Red", 2.2);
        Shape s2 = new Rectangle("Yellow", 2, 4);
          
        System.out.println(s1.toString());
        System.out.println(s2.toString());
    }
}

Output:

Shape constructor called


Circle constructor called
Shape constructor called
Rectangle constructor called
Circle color is Red and area is : 15.205308443374602
Rectangle color is Yellow and area is : 8.0

Encapsulation vs Data Abstraction

1.Encapsulation is data hiding (information hiding) while Abstraction is detail hiding


(implementation hiding).
2. While encapsulation groups together data and methods that act upon the data, data
abstraction deals with exposing the interface to the user and hiding the details of
implementation.
Advantages of Abstraction
1. It reduces the complexity of viewing the things.
2. Avoids code duplication and increases reusability.
3. Helps to increase security of an application or program as only important details are
provided to the user.
Interfaces
Like a class, an interface can have methods and variables, but the methods declared in
interface are by default abstract (only method signature, no body).  
 Interfaces specify what a class must do and not how. It is the blueprint of the class.
 An Interface is about capabilities like a Player may be an interface and any class
implementing Player must be able to (or must implement) move(). So it specifies a set
of methods that the class has to implement.
 If a class implements an interface and does not provide method bodies for all
functions specified in the interface, then class must be declared abstract.

Syntax :
interface <interface_name> {

// declare constant fields


// declare methods that are abstract by default.
}

To declare an interface, use interface keyword. It is used to provide total abstraction. That


means all the methods in interface are declared with empty body and are public and all fields
are public, static and final by default. A class that implement interface must implement all the
methods declared in the interface. To implement interface use implements keyword.

Why do we use interface?


 It is used to achieve total abstraction.
 Since java does not support multiple inheritance in case of class, but by using
interface it can achieve multiple inheritance.
 It is also used to achieve loose coupling.
 Interfaces are used to implement abstraction. So the question arises why use interfaces
when we have abstract classes?
The reason is, abstract classes may contain non-final variables, whereas variables in
interface are final, public and static.

// A simple interface
interface Player
{
    final int id = 10;
    int move();
}
To implement an interface we use keyword: implements

// Java program to demonstrate working of  interface.

import java.io.*;
  
// A simple interface
interface in1
{
    // public, static and final
    final int a = 10;
  
    // public and abstract 
    void display();
}
  
// A class that implements interface.
class testClass implements in1
{
    // Implementing the capabilities of
    // interface.
    public void display()
    {
        System.out.println("Java Programming");
    }
  
    // Driver Code
    public static void main (String[] args)
    {
        testClass t = new testClass();
        t.display();
        System.out.println(a);
    }
}
Output:

Java Programming
10

Example Program: Multiple Inheritance Using Interface

interface vehicleone{
int speed=90;
public void distance();
}

interface vehicletwo{
int distance=100;
public void speed();
}

class Vehicle implements vehicleone,vehicletwo{


public void distance(){
int distance=speed*100;
System.out.println("distance travelled is "+distance);
}
public void speed(){
int speed=distance/100;
}
}

class MultipleInheritanceUsingInterface{
public static void main(String args[]){
System.out.println("Vehicle");
obj.distance();
obj.speed();
}
}
Output

Output is:
distance travelled is 9000

You might also like