Java implements abstract method

Java Guides

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

  1. Abstract classes cannot be instantiated directly.
  2. Abstract classes may be defined with any number, including zero, of abstract and non-abstract methods.
  3. Abstract classes may not be marked as private or final.
  4. An abstract class that extends another abstract class inherits all of its abstract methods as its own abstract methods.
  5. The first concrete class that extends an abstract class must provide an implementation for all of the inherited abstract methods.
public class AbstractClassCompleteExample < public static void main(String[] args) < Animals animals = new Cat(); animals.sound(); animals = new Dog(); animals.sound(); > > abstract class Animals< private String name; // All kind of animals eat food so make this common to all animals public void eat()< System.out.println(" Eating . "); > // The aninals make different sounds. They will provide their own implementation abstract void sound(); > class Cat extends Animals< @Override void sound() < System.out.println("Meoww Meoww . "); > > class Dog extends Animals < @Override void sound() < System.out.println("Woof Woof . "); > >

2. Abstract Method

  1. Abstract methods may only be defined in abstract classes.
  2. Abstract methods may not be declared private or final.
  3. Abstract methods must not provide a method body/implementation in the abstract class for which is it declared.
  4. Implementing an abstract method in a subclass follows the same rules for overriding a method.
abstract class AbstractShape< abstract void draw(); abstract void moveTo(double deltaX, double deltaY); >

3. If a class includes abstract methods, then the class itself must be declared abstract

public abstract class AbstractClassExample < // declare fields // declare nonabstract methods abstract void abstractMethod(); >

4. 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.

abstract class AbstractShape< abstract void draw(); > //The abstract method draw in type Shape can only be defined by an abstract class abstract class Shape extends AbstractShape< @Override abstract void draw(); /*@Override void draw()  // TODO Auto-generated method stub >*/ >

6. When an Abstract Class Implements an Interface

When we create the Java 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.

interface A < void a(); void b(); void c(); void d(); > // The abstract class can also be used to provide some implementation of the interface. //In such case, the end user may not be forced to override all the methods of the interface. abstract class B implements A < public void c() < System.out.println("I am c"); > > class M extends B < public void a() < System.out.println("I am a"); > public void b() < System.out.println("I am b"); > public void d() < System.out.println("I am d"); > > class Test5 < public static void main(String args[]) < final A a = new M(); a.a(); a.b(); a.c(); a.d(); > >

Usage of abstract classes in Real-world Examples

Employee, Contractor, and FullTimeEmployee Example

In this example, we create an abstract Employee class and which contains abstractcalculateSalary () method. Let the subclasses extend Employee class and implementcalculateSalary() method.

Let’s create Contractor and FullTimeEmployee classes as we know that the salary structure for a contractor and full-time employees are different so let these classes to override and implement a calculateSalary() method.

Let’s write source code by referring above class diagram.

Step 1: Let’s first create the abstract superclass named an Employee. Let’s define a method called calculateSalary() as an abstract method in this abstract Employee class. So the method is abstract and we can leave the implementation of this method to the inheritors of the Employee class.

public abstract class Employee < private String name; private int paymentPerHour; public Employee(String name, int paymentPerHour) < this.name = name; this.paymentPerHour = paymentPerHour; > public abstract int calculateSalary(); public String getName() < return name; > public void setName(String name) < this.name = name; > public int getPaymentPerHour() < return paymentPerHour; > public void setPaymentPerHour(int paymentPerHour) < this.paymentPerHour = paymentPerHour; > >

Step 2: The Contractor class inherits all properties from its parent Employee but have to provide its own implementation to calculateSalary() method. In this case, we multiply the value of payment per hour with given working hours.

public class Contractor extends Employee < private int workingHours; public Contractor(String name, int paymentPerHour, int workingHours) < super(name, paymentPerHour); this.workingHours = workingHours; > @Override public int calculateSalary() < return getPaymentPerHour() * workingHours; > >

Step 3: The FullTimeEmployee also has its own implementation of calculateSalary() method. In this case, we just multiply by a constant value of 8 hours.

public class FullTimeEmployee extends Employee < public FullTimeEmployee(String name, int paymentPerHour) < super(name, paymentPerHour); > @Override public int calculateSalary() < return getPaymentPerHour() * 8; > >
public class AbstractClassDemo < public static void main(String[] args) < Employee contractor = new Contractor("contractor", 10, 10); Employee fullTimeEmployee = new FullTimeEmployee("full time employee", 8); System.out.println(contractor.calculateSalary()); System.out.println(fullTimeEmployee.calculateSalary()); > >

Summary

  • An abstract class is a class that is declared with abstract keyword.
  • An abstract method is a method that is declared without an implementation.
  • An abstract class may or may not have all abstract methods. Some of them can be concrete methods
  • A method defined abstract must always be redefined in the subclass, thus making overriding compulsory OR either make subclass itself abstract.
  • Any class that contains one or more abstract methods must also be declared with abstract keyword.
  • There can be no object of an abstract class. That is, an abstract class can not be directly instantiated with the new operator.
  • An abstract class can have parameterized constructors and default constructor is always present in an 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.

    Источник

    Читайте также:  Regular expressions patterns java
Оцените статью