Abstraction

Abstraction in Java or Object oriented programming is a way to segregate implementation from an interface (hiding internal details and showing functionality) and one of the five fundamentals along with Encapsulation, Inheritance, Polymorphism, Class, and Object.

For example: phone call, we don’t know the internal processing.

Abstraction in Java is achieved by using interface and abstract class in Java. An interface or abstract class is something which is not concrete, something which is incomplete.

In order to use interface or abstract class, we need to extend and implement an abstract method with concrete behavior.

One example of Abstraction is creating interface to denote common behavior without specifying any details about how that behavior works e.g. You create an interface called Server which has the start() and stop() method. This is called abstraction of Server because every server should have a way to start and stop and details may differ.

When do you use Abstraction

When you know something needs to be there but not sure how exactly it should look like.

Ex: when creating a class called Vehicle, I know there should be methods like start() and stop() but don’t know how that start and stop method should work, because every vehicle can have different start and stop mechanism e..g some can be started by kicking or some can be by pressing buttons.

So the implementation of those start() and stop() methods should be left to their concrete implementation e.g. Scooter, MotorBike , Car etc.

Java Abstract Class

  • An abstract class is something which is incomplete and you can not create an instance of the abstract class. If you want to use it you need to make it complete or concrete by extended it.
  • A Java class that is declared using the keyword abstract is called an abstract class.
  • An abstract class can have abstract methods and concrete methods or both. Methods with implementation body are concrete methods. But if a class have at least one abstract method, then the class must be declared abstract.
  • An abstract method in Java doesn’t have the body , it’s just a declaration. In order to use an abstract method, you need to override that method in sub class.
  • Java has a concept of abstract classes, abstract method but a variable can not be abstract in Java.
  • An abstract class can have static fields and methods and they can be used the same way as used in a concrete class.
  • To use an abstract class you have to inherit it from another class, provide implementations to the abstract methods in it.
  • 
    public abstract class Animal {
    }
    

When Should I use an Abstract class

We should go for abstract class when we are working with classes that contains similar code. That is, there is a possibility to template behavior and attributes. So, what we gain from this template pattern is avoiding repetition of common code.

Common behavior can be elevated to a super class and provide implementation to it. Then add behavior that cannot be implemented and declare it as abstract.

Classes that are similar to this abstract class will extend it and use the already implemented methods and add implementation for abstract methods.

Java Abstract Method

  • A method that is declared using the keyword abstract is called an abstract method.
  • Abstract methods are declaration only and it will not have implementation. It will not have a method body.
  • A Java class containing an abstract method must be declared as abstract class.
  • Any class inheriting the current class must either override the abstract method or declare itself as abstract.
  • An abstract method can only set a visibility modifier, among public or protected.
  • An abstract method cannot add static or final modifier to the declaration.

public abstract class Animal {
    String name;

    public abstract String getSound();

    public String getName() {
          return name;
    }
}


Extending an Abstract Class

When an abstract class is implemented in Java, generally all its abstract methods will be defined. If one or more abstract method is not defined in the implementing class, then it also should be declared as an abstract class too.

Following is an example class that implements the Animal abstract class. @Override is a Java annotation used to state that this method overrides the method in the super class.


public abstract class Animal {
    String name;

    public abstract String getSound();

    public String getName() {
          return name;
    }
}


public class Lion extends Animal {
    @Override
    public String getSound() {
          return "roar";    
     }
}


Interface in Java

Interface defines set of methods as a contract or as guidelines. The class that is implementing this interface must implement these functionalities in the concrete class.

An interface allows you to guarantee that certain methods exist and return the required types. When the compiler knows this, it can use that assumption to work with unknown classes as if they had certain known behavior.

The interfaces add value when you are building a larger system or a library.

Using references to interfaces instead of classes helps in minimizing the future changes as the user of an interface reference doesn't have to worry about the changes in the underlying concrete implementation.

Whenever there is interface there is Inheritance, as the class which change/ overrides the interface method must be subclass of Interface.

Webdriver interface provides few standard abstract methods to handle the webpages, So when some browser want to access Selenium method, then they have to implement the Webdriver interface and provide implementation to the methods present in the Webdriver interface

You must implement the all the abstract methods present in the interface but the behavior of the methods could be on your own way.


public interface WebDriver {
	// public- access modifier
	// void- return type
	// get - method name
	public void get(String url);
	public String getTitle();
}			

Below Class implements the WebDriver interface.


public class FireFoxDriver implements WebDriver{
	@Override
	public void get(String url) {
		System.out.println("Open webpage");
		// actual code differs, in get method
	}
	@Override
	public String getTitle() {
		System.out.println("Webpage title");
		// actual code differs, in getTite method
		return "title";
	}
}			

If you donot implement the methods present in the WebDriver class then Compiler shows error.

Types of Methods in Interface from Java9

YES, we can have private methods in interface in java 9, private methods could be static or non-static. In both cases, the private method is not inherited by sub-interfaces or implementations.

They are mainly there to improve code re-usability within same interface only – thus improving encapsulation.

Using private methods in interfaces have four rules :

  • Private interface methods cannot be abstract.
  • Private method can be used only inside interface.
  • Private static method can be used inside other static and non-static interface methods.
  • Private non-static methods cannot be used inside private static methods.

Interfaces can below item in interface in Java9 (aka JDK 1.9) :

  • Constant variables
  • Abstract methods
  • Default methods
  • Static methods
  • Private methods
  • Private Static methods

										package frames;
										interface ISam {
											public static final String name = "Java9";
											public void testAbstract();
											default void testDefault(){
												// call non-static method from another non-static method.
												testPrivateNonStatic();
												// call static method from non-static method
												testPrivateStatic();
												
												System.out.println("Default method");
											}
											
											public static void testStatic(){
												System.out.println("static method");
											}
											private void testPrivateNonStatic(){
												System.out.println("private non-static method");
											}
											private static void testPrivateStatic(){
												System.out.println("private static method");
											}
										}
										public class Sample implements ISam{
											@Override
											public void testAbstract() {
												System.out.println("Overridden 'testAbstract' method");
											}
											public static void main(String[] args) {
												System.out.println("constant variable value : "+ name);
												// access static method
												ISam.testStatic();
												// create object for Sample class
												Sample sam = new Sample();
												// we can access default method using object
												sam.testDefault();
												// call abstract method (implementation in Sample class)
												sam.testAbstract();
											}
										}
										

Output


											constant variable value : Java9
											static method
											private non-static method
											private static method
											Default method
											Overridden 'testAbstract' method
										

When to use Abstract Class vs Interface in Java

You can go for java interface if you only know the name of methods your class should have e.g. for Server it should have start() and stop() method but we don’t know how exactly these start and stop method will work.

If you know some of the behavior while designing class and that would remain common across all subclasses add that into an abstract class.

An interface like Runnable interface is a good example of abstraction in Java which is used to abstract task executed by multiple threads. Callable is another good abstract of a task which can return value.

A variable declared inside interface must be public static final variables(constants), it cannot have any other modifier. And Methods inside Interface must not be static, final, native or strictfp.

Can an Abstract Class have Constructor in Java?

Yes, an abstract class can have constructor in Java. It can be a useful option to enforce class constraints like setting up a field.


public abstract class Animal {
    String name;

    public Animal(String name) {
          this.name = name;
    }

    public String getName() {
          return name;
    }

    public abstract String getSound();
}


This abstract class defines a constructor with an argument that is used to setup the field name.

Classes that extends this abstract class should define a constructor with implicit super() call to the super abstract class. Otherwise we will get an error as
implicit super constructor Animal() is undefined. Must explicitly invoke another constructor.

This is to do some initialization before instantiation.


public class Lion extends Animal {
    public Lion(String name) {
          super(name);
    }

    @Override
    public String getSound() {
          return "roar";
    }
}


Can an Abstract class be final in Java?

No, an abstract class cannot be declared as final in Java. Because it will completely negate the purpose of an abstract class.

An abstract class should be extended to create instances. If it is declared final, then it cannot be extended and so an abstract class cannot be declared as final.

Difference between Abstraction and Encapsulation in Java

  • First difference between Abstraction and Encapsulation is that, Abstraction is implemented in Java using interface and abstract class while Encapsulation is implemented using private, package-private and protected access modifier.
  • Encapsulation is also called data hiding.
  • Design principles “programming for interface than implementation? is based on abstraction and “encapsulate whatever changes? is based upon Encapsulation.

Abstraction: Things to Remember

  • Use abstraction if you know something needs to be in class but the implementation of that varies. Abstraction is actually resulting of thought process and it really need good experience of both domain and Object oriented analysis and design to come up with good abstraction for your project.
  • In Java, you can not create an instance of the abstract class using the new operator, its compiler error. Though abstract class can have a constructor.
  • abstract is a keyword in Java, which can be used with both class and method. Abstract class can contain both abstract and concrete method. An abstract method doesn’t have the body, just declaration.
  • A class automatically becomes abstract class when any of its methods declared as abstract.
  • abstract method doesn’t have method body.
  • In Java, a variable can not be made abstract , its only class or methods which would be abstract.
  • If a class extends an abstract class or interface it has to provide implementation to all its abstract method to be a concrete class. alternatively, this class can also be abstract.

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Recent Addition

new tutorial Protractor Online Training : We have closed registration for training

Please do email to chercher.tech@gmail.com for any queries

If you already registered then please do check your email for the Webex link