0% found this document useful (0 votes)
11 views7 pages

Understanding Abstract Classes in Java

An abstract class in Java is declared with the abstract keyword and cannot be instantiated unless inherited by a subclass that implements its abstract methods. The document provides an example of an abstract class 'Employee' and a concrete subclass 'Salary' that implements the abstract method 'computePay'. It also explains the rules for declaring abstract methods and the necessity for subclasses to provide implementations for them.

Uploaded by

upipersonal8465
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views7 pages

Understanding Abstract Classes in Java

An abstract class in Java is declared with the abstract keyword and cannot be instantiated unless inherited by a subclass that implements its abstract methods. The document provides an example of an abstract class 'Employee' and a concrete subclass 'Salary' that implements the abstract method 'computePay'. It also explains the rules for declaring abstract methods and the necessity for subclasses to provide implementations for them.

Uploaded by

upipersonal8465
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Abstract Class

A class which contains the abstract keyword in its declaration is known as


abstract class.

 Abstract classes may or may not contain abstract methods ie., methods with out
body ( public void get(); )

 But, if a class have at least one abstract method, then the class must be
declared abstract.

 If a class is declared abstract it cannot be instantiated.

 To use an abstract class you have to inherit it from another class, provide
implementations to the abstract methods in it.

 If you inherit an abstract class you have to provide implementations to all the
abstract methods in it.

Example
This section provides you an example of the abstract class to create an abstract class
just use the abstract keyword before the class keyword, in the class declaration .
/* File name : [Link] */

public abstract class Employee

private String name;

private String address;

private int number;

public Employee(String name, String address, int number)

[Link]("Constructing an Employee");

[Link] = name;

[Link] = address;

[Link] = number;

public double computePay()

{
[Link]("Inside Employee computePay");

return 0.0;

public void mailCheck()

[Link]("Mailing a check to " + [Link]

+ " " + [Link]);

public String toString()

return name + " " + address + " " + number;

public String getName()

return name;

public String getAddress()

return address;

public void setAddress(String newAddress)

address = newAddress;

public int getNumber()

return number;

You can observe that except abstract methods the Employee class is same
as normal class in Java. The class is now abstract, but it still has three fields,
seven methods, and one constructor.
Now you can try to instantiate the Employee class as shown below:

/* File name : [Link] */

public class AbstractDemo

public static void main(String [] args)

/* Following is not allowed and would raise error */

Employee e = new Employee("George W.", "Houston, TX", 43);

[Link]("\n Call mailCheck using Employee reference--");

[Link]();

When you compile the above class, it gives you the following error:

[Link]: Employee is abstract; cannot be instantiated

Employee e = new Employee("George W.", "Houston, TX", 43);

1 error

Inheriting the Abstract Class:


We can inherit the properties of Employee class just like concrete class as
shown below:

/* File name : [Link] */

public class Salary extends Employee

private double salary; //Annual salary

public Salary(String name, String address, int number, double

salary)

super(name, address, number);

setSalary(salary);
}

public void mailCheck()

[Link]("Within mailCheck of Salary class ");

[Link]("Mailing check to " + getName()

+ " with salary " + salary);

public double getSalary()

return salary;

public void setSalary(double newSalary)

if(newSalary >= 0.0)

salary = newSalary;

public double computePay()

[Link]("Computing salary pay for " + getName());

return salary/52;

Here, you cannot instantiate the Employee class, but you can instantiate the
Salary Class, and using this instance you can access the all the three fields
and seven methods of Employee class as shown below.

/* File name : [Link] */

public class AbstractDemo

public static void main(String [] args)

{
Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);

Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);

[Link]("Call mailCheck using Salary reference --");

[Link]();

[Link]("\n Call mailCheck using Employee reference--");

[Link]();

This produces the following result:

Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference --
Within mailCheck of Salary class
ailing check to Mohd Mohtashim with salary 3600.0

Call mailCheck using Employee reference--


Within mailCheck of Salary class
ailing check to John Adams with salary 2400.

Abstract Methods:
If you want a class to contain a particular method but you want the actual
implementation of that method to be determined by child classes, you can
declare the method in the parent class as abstract.

 abstract keyword is used to declare the method as abstract.

 You have to place the abstract keyword before the method name in the method
declaration.

 An abstract method contains a method signature, but no method body.

 Instead of curly braces an abstract method will have a semoi colon ( ; ) at the
end.
Below given is an example of the abstract method.

public abstract class Employee

private String name;

private String address;

private int number;

public abstract double computePay();

//Remainder of class definition

Declaring a method as abstract has two consequences:

 The class containing it must be declared as abstract.

 Any class inheriting the current class must either override the abstract method
or declare itself as abstract.

Note: Eventually, a descendant class has to implement the abstract


method; otherwise, you would have a hierarchy of abstract classes that
cannot be instantiated.

Suppose Salary class is inherits the Employee class, then it should


implement the computePay() method as shown below:

/* File name : [Link] */

public class Salary extends Employee

private double salary; // Annual salary

public double computePay()

[Link]("Computing salary pay for " + getName());

return salary/52;
}

//Remainder of class definition

Common questions

Powered by AI

An abstract class in Java cannot be instantiated directly, but it can be instantiated indirectly through a subclass that provides implementations for its abstract methods. For example, the abstract class Employee cannot be directly instantiated. However, by creating a subclass, Salary, that implements the required abstract methods of Employee, you can instantiate Salary objects that thereby indirectly utilize the structure and methods of Employee. This process allows developers to define general behaviors and attributes in abstract classes while realizing specific functionality in concrete subclasses .

Failing to implement an abstract method in a subclass results in a compile-time error, as Java requires concrete subclasses to provide implementations for all abstract methods defined in their superclass unless the subclass itself is declared abstract. This error reinforces the contract established by the abstract method and ensures that all subclasses provide requisite functionality. The compile-time check prevents runtime errors related to missing method implementations and guarantees correct class behavior when instantiated .

Providing at least one abstract method in an abstract class solidifies the design principle of forcing subclasses to implement specific behavior, thereby ensuring that all derivatives have a cohesive and consistent structure. It facilitates the Template Method design pattern where the abstract class defines the skeleton of an algorithm, and subclasses implement the specific steps. This approach promotes code reuse and ensures that subclasses adhere to a defined protocol or interface .

A subclass of an abstract class is not required to implement an abstract method from its superclass if the subclass itself remains abstract. This allows the subclass to inherit the abstract method while deferring the implementation requirement to further subclasses. This scenario might occur in a multi-level inheritance hierarchy where intermediate classes serve as placeholders for common functionality that still requires specific method implementations in concrete subclasses .

Declaring a method as abstract means that the method has a signature but no implementation; it essentially serves as a placeholder for methods that must be defined in subsequent subclasses. When a method is abstract, the class containing it must also be declared as abstract. Child classes inheriting from such an abstract class must override the abstract method to provide specific implementations unless the child class is also declared abstract. If no subclass provides implementations for the abstract methods, the class hierarchy will remain composed only of abstract classes, which cannot be instantiated .

Java abstract classes support encapsulation by allowing developers to define fields and concrete methods that can be inherited by subclasses, thus packaging related operations and data closely together. Despite having abstract methods that necessitate external implementation, an abstract class still encapsulates common attributes and behaviors, which provides a controlled structure and interface for any concrete subclass implementations. Subclasses then have flexibility in realizing these encapsulated abstract methods while maintaining the encapsulated access to fields and methods provided by the abstract class .

A developer might choose to design a class as abstract when they want to provide a common template for a set of related classes but defer the implementation of some methods to the subclasses. Abstract classes are useful for defining a base class with common fields and method implementations while leaving the specific implementations of certain methods to the subclasses. This approach is beneficial in adhering to the DRY principle by minimizing code duplication and ensuring all subclasses conform to a specific protocol or interface for certain behaviors .

An abstract class differs from a regular concrete class primarily in its ability to be instantiated and in its method definitions. An abstract class cannot be instantiated; it includes the abstract keyword and may contain abstract methods, which are methods without bodies that require implementation in subclasses. In contrast, a concrete class can be instantiated directly and must have fully defined methods with bodies .

You cannot instantiate an abstract class directly. Instead, you can use it by inheriting from it and then instantiating the subclass. For example, you cannot create an instance of the abstract class Employee directly. However, you can create a subclass, Salary, that extends Employee and implements the abstract methods. Then you can instantiate the Salary class and use it to access fields and methods inherited from Employee, such as mailCheck().

When a method in a subclass overrides an abstract method in its superclass, calling this overridden method will execute the subclass's version of the method. For instance, in the example where the Salary class overrides the mailCheck method from the Employee abstract class, calling mailCheck on a Salary object prints "Within mailCheck of Salary class" followed by "Mailing check to [Name] with salary [Amount]". This shows that even when using an Employee reference type, the actual method executed is that of the Salary class, demonstrating polymorphism .

You might also like