What are abstract classes and interfaces in java

Difference between Abstract Class and Interface in Java

Abstract class and interface are both used to define contracts in object-oriented programming, but there are some key differences between them.

Difference between abstract class and interface:-

Definition: An abstract class is a class that cannot be instantiated and can contain both abstract and non-abstract methods. An interface, on the other hand, is a contract that specifies a set of methods that a class must implement.

Method implementation: In an abstract class, some methods can be implemented, while others are left abstract, meaning that they have no implementation and must be overridden by concrete subclasses. In contrast, all methods in an interface are by default abstract and must be implemented by any class that implements the interface.

Inheritance: A class can inherit from only one abstract class, but it can implement multiple interfaces. This is because an abstract class represents a type of object, while an interface represents a set of behaviors.

Access modifiers: Abstract classes can have access modifiers such as public, protected, and private for their methods and properties, while interfaces can only have public access.

Variables: An abstract class can have member variables, while an interface cannot.

In summary, abstract classes are used to provide a base class for concrete subclasses to inherit from, while interfaces are used to define a set of methods that a class must implement. Abstract classes can have implemented and abstract methods, while interfaces can only have abstract methods. Classes can inherit from only one abstract class, but can implement multiple interfaces.

Читайте также:  Все возможности словаря питон

As we know that abstraction refers to hiding the internal implementation of the feature and only showing the functionality to the users. i.e. showing only the required features, and hiding how those features are implemented behind the scene. Whereas, an Interface is another way to achieve abstraction in java. Both abstract class and interface are used for abstraction, henceforth Interface and Abstract Class are required prerequisites.

Abstract Class vs Interface

Abstract class vs Interface

  • Type of methods: Interface can have only abstract methods. Whereas, an abstract class can have abstract method and concrete methods. From Java 8, it can have default and static methods also. From Java 9, it can have private concrete methods as well.
  • Note : Concrete methods are those methods which has their complete definition but they can also be overriden in the inherited class. However, if we make the concrete method as “FINAL” it cannot be overrided in the inherited class because declaring a method as final means – its implementation is complete.
  • Final Variables: Variables declared in a Java interface are by default final. An abstract class can contain non-final variables.
  • Type of variables: Abstract class can have final, non-final, static and non-static variables. The interface has only static and final variables.
  • Implementation: Abstract class can provide the implementation of the interface. Interface can’t provide the implementation of an abstract class.
  • Inheritance vs Abstraction: A Java interface can be implemented using the keyword “implements” and an abstract class can be extended using the keyword “extends”.
  • Multiple implementations: An interface can extend one or more Java interfaces; an abstract class can extend another Java class and implement multiple Java interfaces.
  • Multiple Inheritance: Multiple inheritance can be partially achieved by the use of interfaces , whereas the same can’t be done by the use of abstract classes. Because in Java, one class can implement multiple Interfaces, but one class cannot extend from multiple other classes because that’s just not possible in java as that would lead to the diamond problem.
  • Accessibility of Data Members: Members(variables) of a Java interface are final by default. A Java abstract class can have class members like private, protected, etc.

Features of abstract class:-

  1. An abstract class is a special type of class in object-oriented programming that cannot be instantiated directly. Instead, it serves as a blueprint or template for other classes to be derived from. Some of the key features of an abstract class include:
  2. Cannot be instantiated: Abstract classes cannot be directly instantiated, which means you cannot create objects of an abstract class.
  3. Contains at least one pure virtual function: Abstract classes must contain at least one pure virtual function, which means that the function has no implementation and must be implemented by any derived classes.
  4. Can contain both abstract and non-abstract methods: Abstract classes can have both abstract and non-abstract methods. Non-abstract methods have a complete implementation and can be called directly.
  5. Can have constructors and destructors: Abstract classes can have constructors and destructors like any other class.
  6. Can have member variables: Abstract classes can have member variables, which are variables that belong to an object of the class.
  7. Can be used as a base class: Abstract classes can be used as a base class for other classes, which means that they can be inherited by other classes.
  8. Overall, abstract classes are used to define a common interface or behavior that can be shared by multiple related classes, but with specific implementations in each derived class.

Example 1 : (For Abstract Class )

Источник

Abstract Methods and Classes

An abstract class is a class that is declared abstract —it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.

An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:

abstract void moveTo(double deltaX, double deltaY);

If a class includes abstract methods, then the class itself must be declared abstract , as in:

public abstract class GraphicObject < // declare fields // declare nonabstract methods abstract void draw(); >

When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract .

Note: Methods in an interface (see the Interfaces section) that are not declared as default or static are implicitly abstract, so the abstract modifier is not used with interface methods. (It can be used, but it is unnecessary.)

Abstract Classes Compared to Interfaces

Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation. However, with abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods. With interfaces, all fields are automatically public, static, and final, and all methods that you declare or define (as default methods) are public. In addition, you can extend only one class, whether or not it is abstract, whereas you can implement any number of interfaces.

Which should you use, abstract classes or interfaces?

  • Consider using abstract classes if any of these statements apply to your situation:
    • You want to share code among several closely related classes.
    • You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
    • You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.
    • You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.
    • You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
    • You want to take advantage of multiple inheritance of type.

    An example of an abstract class in the JDK is AbstractMap , which is part of the Collections Framework. Its subclasses (which include HashMap , TreeMap , and ConcurrentHashMap ) share many methods (including get , put , isEmpty , containsKey , and containsValue ) that AbstractMap defines.

    An example of a class in the JDK that implements several interfaces is HashMap , which implements the interfaces Serializable , Cloneable , and Map . By reading this list of interfaces, you can infer that an instance of HashMap (regardless of the developer or company who implemented the class) can be cloned, is serializable (which means that it can be converted into a byte stream; see the section Serializable Objects), and has the functionality of a map. In addition, the Map interface has been enhanced with many default methods such as merge and forEach that older classes that have implemented this interface do not have to define.

    Note that many software libraries use both abstract classes and interfaces; the HashMap class implements several interfaces and also extends the abstract class AbstractMap .

    An Abstract Class Example

    In an object-oriented drawing application, you can draw circles, rectangles, lines, Bezier curves, and many other graphic objects. These objects all have certain states (for example: position, orientation, line color, fill color) and behaviors (for example: moveTo, rotate, resize, draw) in common. Some of these states and behaviors are the same for all graphic objects (for example: position, fill color, and moveTo). Others require different implementations (for example, resize or draw). All GraphicObject s must be able to draw or resize themselves; they just differ in how they do it. This is a perfect situation for an abstract superclass. You can take advantage of the similarities and declare all the graphic objects to inherit from the same abstract parent object (for example, GraphicObject ) as shown in the following figure.

    Classes Rectangle, Line, Bezier, and Circle Inherit from GraphicObject

    First, you declare an abstract class, GraphicObject , to provide member variables and methods that are wholly shared by all subclasses, such as the current position and the moveTo method. GraphicObject also declares abstract methods for methods, such as draw or resize , that need to be implemented by all subclasses but must be implemented in different ways. The GraphicObject class can look something like this:

    abstract class GraphicObject < int x, y; . void moveTo(int newX, int newY) < . >abstract void draw(); abstract void resize(); >

    Each nonabstract subclass of GraphicObject , such as Circle and Rectangle , must provide implementations for the draw and resize methods:

    class Circle extends GraphicObject < void draw() < . >void resize() < . >> class Rectangle extends GraphicObject < void draw() < . >void resize() < . >>

    When an Abstract Class Implements an Interface

    In the section on Interfaces , it was noted that a class that implements an interface must implement all of the interface’s methods. It is possible, however, to define a class that does not implement all of the interface’s methods, provided that the class is declared to be abstract . For example,

    abstract class X implements Y < // implements all but one method of Y >class XX extends X < // implements the remaining method in Y >

    In this case, class X must be abstract because it does not fully implement Y , but class XX does, in fact, implement Y .

    Class Members

    An abstract class may have static fields and static methods. You can use these static members with a class reference (for example, AbstractClass.staticMethod() ) as you would with any other class.

    Источник

Оцените статью