0% found this document useful (0 votes)
12 views10 pages

Java Abstraction and Abstract Classes

The document explains Java abstraction, which is the process of hiding implementation details and exposing only functionality to the user, achieved through abstract classes and interfaces. It describes how to declare abstract classes and methods, along with examples of how to implement and inherit these classes in Java. The document also highlights the importance of providing implementations for abstract methods in derived classes.

Uploaded by

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

Java Abstraction and Abstract Classes

The document explains Java abstraction, which is the process of hiding implementation details and exposing only functionality to the user, achieved through abstract classes and interfaces. It describes how to declare abstract classes and methods, along with examples of how to implement and inherit these classes in Java. The document also highlights the importance of providing implementations for abstract methods in derived classes.

Uploaded by

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

Java - Abstraction

As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example,
when you consider the case of e-mail, complex details such as what happens as soon as you send
an e-mail, the protocol your e-mail server uses are hidden from the user. Therefore, to send an e-
mail you just need to type the content, mention the address of the receiver, and click send.

Java Abstraction
Abstraction is a process of hiding the implementation details from the user, only the functionality
will be provided to the user. In other words, the user will have the information on what the object
does instead of how it does it. In Java programming, abstraction is achieved using Abstract classes
and interfaces.

Java Abstract Classes


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

Java abstract classes may or may not contain abstract methods, i.e., methods without body
( public void get(); )
But, if a class has 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: Java Abstract Class


This section provides you an example of the Java Abstract Class. To create an abstract class in Java,
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 in the following way −

Open Compiler
/* 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]();
}
}

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;
}
}

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

Learn Java in-depth with real-world projects through our Java certification course. Enroll and
become a certified expert to boost your career.

Inheriting the Java Abstract Class


We can inherit the properties of Employee class just like concrete class in the following way −

Example: Inheriting the Abstract Class in Java


/* 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 "
}

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 all the three fields and seven methods of Employee class as shown
below.

Open Compiler

/* 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]();
}
}
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;
}
}
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 "
}

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;
}
}

Output

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

Call mailCheck using Employee reference--


Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.0

Java 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 an
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.

Example 1: Implementing Abstract Method in Java


Following 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 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
}

Example 2: Implementing Abstract Method in Java


Following example showcases the concept of abstract method.
Open Compiler

/* File name : [Link] */


public class AbstractDemo {
public static void main(String [] args) {
Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
[Link]("salary: " + [Link]());
}
}
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 abstract double computePay();


// Remainder of class definition

public String getName() {


return name;
}

public void setName(String name) {


[Link] = name;
}

public String getAddress() {


return address;
}

public void setAddress(String address) {


[Link] = address;
}

public int getNumber() {


return number;
}

public void setNumber(int number) {


[Link] = number;
}
}
class Salary extends Employee {
private double salary; // Annual salary

public Salary(String name, String address, int number, double salary) {


super(name, address, number);
[Link] = salary;
}

public double computePay() {


[Link]("Computing salary pay for " + getName());
return salary/52;
}
// Remainder of class definition
}

Output

Constructing an Employee
Computing salary pay for Mohd Mohtashim
salary: 69.23076923076923

Common questions

Powered by AI

Having a class hierarchy with abstract classes that are not fully implemented means that none of the involved classes can be instantiated, and the hierarchy is essentially not operational until concrete implementations for abstract methods are provided. Java handles such structures by enforcing that any subclass in the hierarchy must either implement all inherited abstract methods or declare itself as abstract. This enforces a clear separation between interface and implementation, ensuring that any usable subclass has complete and practical behavior .

Abstract methods facilitate interface implementation by providing a framework that obliges concrete subclasses to implement method signatures defined in an interface. Interfaces serve as a contract that specifies what behaviors a class must implement, without dictating how. By implementing these abstract method contracts within concrete subclasses, a programmer adheres to Java's programming principles of encapsulation and polymorphism, promoting modularity and flexibility in code design. This approach supports the design of scalable and maintainable applications .

The inheritance mechanism in Java allows derived classes to implement abstract methods by extending abstract classes. For instance, an abstract class 'Employee' with an abstract method 'computePay()' requires a subclass, such as 'Salary', to provide its specific implementation for 'computePay()'. The 'Salary' class extends 'Employee', and it is in 'Salary' that the 'computePay()' method is defined to calculate a salary divided by 52 weeks, thus fulfilling the contract of the abstract method declared in 'Employee' .

Java achieves abstraction by using abstract classes and interfaces. Abstract classes in Java are declared with the 'abstract' keyword in their definition and may contain abstract methods (methods without a body) that must be implemented by subclasses. Interfaces, on the other hand, are even more abstract than abstract classes. They can only declare methods that implementing classes must define, thus hiding the implementations from the user. These constructs allow Java to present only the necessary details to the user, while the complex implementation details remain hidden .

When attempting to instantiate an abstract class in Java, the error message generated is: 'Employee is abstract; cannot be instantiated.' This message indicates that the abstract class is incomplete as it contains one or more abstract methods that do not have implementations, emphasizing that abstract classes are meant to be extended rather than instantiated directly .

It is essential for any class inheriting an abstract class to either implement all inherited abstract methods or declare itself as abstract to ensure that the class is fully operational and can be instantiated if required. This requirement enforces Java's design principles of abstraction and polymorphism. It ensures that subclasses provide concrete implementations for behaviors defined as necessary by their base class, promoting a cohesive and complete object-oriented approach in application design .

It is not possible to instantiate an abstract class in Java because an abstract class is designed to provide a base implementation and abstract methods that subclasses are expected to implement. Instantiation of abstract classes would defeat the purpose of abstraction, where the goal is to hide implementation details and force the subclasses to complete the implementation. Thus, instantiation is only possible for concrete implementations of these abstract classes .

Abstract classes in Java allow for shared implementation code and full method inheritance, which is useful for resource initialization or when sharing code among related classes. However, they limit inheritance to a single abstract class due to Java’s single inheritance model. Interfaces, conversely, provide a stronger form of abstraction as they only define method signatures, permitting the implementation across multiple unrelated classes without inheritance limitations. However, this can lead to code duplication as interfaces cannot initialize or share state. The choice between the two depends on the specific design requirements, such as the need for shared code or multiple inheritance .

In Java, abstract methods are declared within an abstract class using the 'abstract' keyword followed by the method signature without a body. The implementation of these abstract methods is crucial for concrete subclasses because, without providing implementations, these subclasses remain abstract and cannot be instantiated. Abstract methods serve as a contract that obliges subclasses to provide specific functionality, thus ensuring that subclasses can be utilized as their instantiated objects with complete behavior .

Even though an abstract class cannot be instantiated directly, its constructor is executed when a derived class is instantiated. This occurs because the derived class implicitly calls the constructor of its super class as part of its own instantiation process. This process is necessary to initialize the fields and perform any necessary setup defined in the abstract class, ensuring that all inherited properties are properly initialized before the extended class adds its own specific initializations .

You might also like