Data Abstraction with examples of java program
Answers
Answer:
Abstraction is a process of hiding the implementation details from the user. Оnly the functionality will be provided to the user. In Java, abstraction is achieved using abstract classes and interfaces. We have a more detailed explanation on Java Interfaces, if you need more info about Interfaces please read this tutorial first.
Abstraction is one of the four major concepts behind object-oriented programming (OOP). OOP questions are very common in job interviews, so you may expect questions about abstraction on your next Java job interview.
Java Abstraction Example
To give an example of abstraction we will create one superclass called Employee and two subclasses – Contractor and FullTimeEmployee. Both subclasses have common properties to share, like the name of the employee and the the amount of money the person will be paid per hour. There is one major difference between contractors and full-time employees – the time they work for the company. Full-time employees work constantly 8 hours per day and the working time of contractors may vary.
Java abstract class example
Java abstract class example
Lets first create the superclass Employee. Note the usage of abstract keyword in class definition. This marks the class to be abstract, which means it can not be instantiated directly. We define a method called calculateSalary() as an abstract method. This way you leave the implementation of this method to the inheritors of the Employee class.
package net.javatutorial;
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;
}
}