DEV Community

loading...

JAVA: OOP (Abstraction)

supriya2371997 profile image Supriya Kolhe Updated on ・6 min read

Q1: OOPS: Abstraction?
Q2: interface?
Q3. abstract class?
Q4: Why can’t static methods be abstract in Java?
Q5: Advantages of Abstraction?
Q6: Why can’t we create an object of an Abstract Class?
Q7: Data Encapsulation vs Data Abstraction?
Q8: Abstract Class vs Interface?
Q9: When to use abstract class?
Q10: when to use interface?

1. Abstraction:-

1.1 process of hiding implementation

showing essential features and hiding non-essential features from the user.

1.2 for example, the remote is an interface between user and TV. It can be operated using various buttons, but the user is unaware of the internal part of the remote(i.e. circuits). It is so because the user does not need to know the details except the one that helps him operate the remote.
1.3 another example can be a login or registration form. The user is unaware/does not need to know how things work behind the curtains i.e UI.
1.4 it is a collection of abstract methods

ways to achieve abstraction:-

  1. using the interface
  2. using abstract class

2. Using Interface:-

2.1 Consider an example of the remote. It only works as an interface between the TV and the user. It can't be used to operate any other device/machine. i.t. it contains all the necessary functionalities which the user might require while hiding the implementation details from the user.
2.2 similarly interface contains empty methods and can contain variables also.

it means that interfaces don't provide any implementation details and it's up to classes/clients to provide the implementation details fro the method/methods when they implement the interface.

2.3 a class can use implements keyword to implement the interface and provide the implementation of the interface method
2.4 a java class can implement the interface in order to provide the implementation of the methods using interface
2.5 interface provide sets of rules for classes and tell them what to do and not to do.

in case class does not provide an implementation for all the methods of the interface, then the class must be declared abstract

Simple Example:

interface printable
{
    void start();
    void stop();
    int off=0;
    void pressed(int key);
}
class InterfaceExample implements printable
{
    int off=1;
    @Override
    public void start()
    {
        System.out.println("Started");
    }
    @Override
    public void stop()
    {
        System.out.println("\nvariable from interface : "+printable.off+"\nStopped ");
    }
    @Override
    public void pressed(int key)
    {
                //printable.off=1;
        System.out.println("\nvariable from interface : "+off+"\nPressed key number "+key);
    }
    public static void main(String args[])
    {
        InterfaceExample obj = new InterfaceExample();
        obj.start();obj.pressed(23);
        obj.stop();

    }
}
/*Started

variable from interface : 1
Pressed key number 23

variable from interface : 0
Stopped*/
Enter fullscreen mode Exit fullscreen mode

-:here, we have created an interface with methods and variable which we are implementing in class and also trying to see whether a change of value inside the method will affect the interface variable i.e. off variable.

changing variable value inside the method does not affect interface value

-:in the above example if we uncomment the line "printable.off=1;" and then execute the code, it will throw a compile-time error

InterfaceExample.java:24: error: cannot assign a value to final variable off
                printable.off=1;
                         ^
1 error
Enter fullscreen mode Exit fullscreen mode

static method inside interface Example:

interface Jump 
{
    static int getHeight() 
    {
        return 1;
    }
}
class Cat implements Jump 
{
    public void jump() 
    {
        System.out.println(“Jumping height “ + getHeight());//COMPILE TIME ERROR
    }
}
Enter fullscreen mode Exit fullscreen mode

-:above code will not compile, since it is calling for the getHeight() which is supposed to be inside Kangaroo.

in order to execute the code, one change needs to be done i.e.

System.out.println(“Jumping height “ + Jump.getHeight());
Enter fullscreen mode Exit fullscreen mode

nested interface Example:

interface OuterInterface 
{
    interface InnerInterface 
    {        
    }

}

class ImplementingC implements OuterInterface.InnerInterface 
{
} 
Enter fullscreen mode Exit fullscreen mode

nested interface Example:

class OuterC
{
    interface InnerInterface 
    {        
    }
}

class ImplementingC implements OuterClass.InnerInterface 
{    
}
Enter fullscreen mode Exit fullscreen mode

interface extending interface Example:

public interface Teacher 
{
   public void Name(String name);
   public void Age(int age);
}

public interface Computer extends Teacher 
{
   public void MonthlyAttendance(int attendance);
   public void Salary(String sal);
   public void City(String city);
}
Enter fullscreen mode Exit fullscreen mode

-:here the class that implements Computer interface must provide an implementation for both Computer and Teacher interface as it is extended by the Computer interface.

class of interface is also created after compiler compiles the code, i.e. printable.class file will be created after the compilation is done

Facts about interface:-

-:all members i.e. both methods and variables/fields of an interface are public
-:all the methods are public, abstract by default

except static and default

-:all the fields are public, static, final by default
-:an interface can extend another interface using extend keyword.
-:interface can contain static methods

Interface features:-

-:provide the total abstraction
-:help achieve multiple inheritance as java doesn't support multiple inheritances.

one class can implement several interfaces which can also be called as multiple interface implementation.

-:help achieve loose coupling in design patterns implementation

loose coupling means independent behaviour, for example, class A only knows about class B what class B has exposed through its interface.

3. using abstract class:-

3.1 provide total abstraction where all the methods are empty and field variables are public static and final by default
3.2 use keyword abstract before the class declaration and method declaration
3.3 we can't create an object of an abstract class

-:but we can define its constructor which can only be invoked in the constructor of its subclass
-:subclass constructor can access a superclass constructor to initialize its variable which might be needed in the subclass

3.4 they can contain both abstract and non-abstract methods.

they can't contain the body of the abstract method

3.5 if the subclass is not implementing the abstract methods then we have to make it abstract explicitly

if the class contains an abstract method, then it must be defined as abstract

3.6 abstract class is used to provide the most common feature that is specific to various classes.

subclasses can provide a different implementation of those methods according to their requirement

Eaxmple:-

abstract class Animal
{
    public abstract void Like();
    public void doTheyHaveLegs()
    {
        System.out.println("Yes, animals have legs");
    }
}

class Dog extends Animal
{
    @Override
    public void Like()
    {
        System.out.println("Dog like to cuddle.");
    }
}

class Lion extends Animal
{
    @Override
    public void Like()
    {
        System.out.println("Lion like to Growl");
    }
}



class TestAnimal
{
    public static void main(String[] args)
    {
        Animal Dog = new Dog();
        Dog.Like();

        Animal Lion = new Lion();
        Lion.Like();
        Dog.doTheyHaveLegs();
        Lion.doTheyHaveLegs();
    }
}
/*
Dog like to cuddle.
Lion like to Growl
Yes, animals have legs
Yes, animals have legs
*/
Enter fullscreen mode Exit fullscreen mode

3.7 Here Animal is an abstract class which share a common property of animal with Dog and Lion class, which are implementing Like() of Animal abstract class

Animal class has both abstract and non-abstract methods in it.

4. Why can’t static methods be abstract in Java:-

4.1 there are two points to remembers

static keyword stated that static method can't be overridden.
abstract stated that the implementation of the method must be provided by the subclass

4.2 here as you can see, both the points contradict with each other, thus resulting it is not possible to make an abstract method static

although, abstract class may contain static methods

Alt Text

6. Why can’t we create an object of an Abstract Class:-

6.1 it is not very useful to do so because there would not be any actual implementation of the called method.

7. Data Encapsulation vs Data Abstraction:-

Data Encapsulation is hiding data or information

Abstraction is hiding the implementation details

Encapsulation binds the data members and methods together

data abstraction deals with showing the external details of an entity to the user and hiding the details of its implementation.

Encapsulation hides the data

abstraction provides access to a specific part of data

8. Abstract Class vs Interface:-

"abstract" keyword is used

"interface" keyword is used

We can extend an abstract class using the extends keyword

We can implement an interface using the implements keyword

can have both final, non-final, static and non-static variables

can only have final and static variables that are declared by default

speed is fast as compared to the interface

speed is slow as compared to abstract class

may or may not have variables declared as final

variables are by default declared as final

can have all access modifiers

only public access modifier is allowed

can have both abstract and non-abstract or concrete methods

can only have abstract methods,but, from version 8 of Java, the interface supports static and non-static methods too.

can have constructors

can not have constructors

Abstract classes do not support Multiple Inheritance, but, a class can extend only a single abstract class but can implement multiple Java interfaces

Interface support Multiple Inheritance

abstract class is used to avoid independence

interface is used when Future enhancement is needed

9. When to use abstract class:-

9.1 when some related classes that need to share the same lines of code
9.2 is there is a requirement of using access modifiers other than public

10. When to use interface:-

10.1 to achieve 100% abstraction
10.2 to achieve multiple inheritance
10.3 to specify the behaviour of a particular data type, irrespective of who implements its behaviour

Please comment if you have any feedback or suggestions

Discussion (0)

Forem Open with the Forem app