Why And When To Use Abstract Classes and Methods?
To achieve security – hide certain details and only show the important details of an object.
Abstract Classes and Methods
Data abstraction is the process of hiding certain details and showing only essential information to the user.
Remember from the Inheritance chapter that we use the extends
keyword to inherit from a class.
The abstract
keyword is a non-access modifier, used for classes and methods:
- Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).
- Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from).
Example
// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep() {
System.out.println("Zzz");
}
}
// Subclass (inherit from Animal)
class Pig extends Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
}
class Main {
public static void main(String[] args) {
Animal myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
output:
The pig says: wee wee
Zzz
practices:
abstract class Madam{//parent claas
abstract void studysubject();
abstract void assignment();
public static void main(String[] args){
//can not be create object
}
void studyforteacher(){
System.out.println("No Way");
}
}
/////////////////////////////////////////////////////////////////////////////
class Student extends Madam{
public static void main(String[] args){
Student aravind = new Student();
//aravind.play();
//aravind.studyforteacher();
Madam hari= new Student();
hari.assignment();
hari.studysubject();
hari.studyforteacher();
hari.play();//can not access the child class method error
}
///////////////////////////
void assignment(){
System.out.println("I am Not completed Madam");
}
void studysubject(){
System.out.println("I am can not study everday ");
}
///////////child class method/////////
void play(){
System.out.println("I am playing for cricket");
}
}
output:
aravind@aravind-Gateway-NE46Rs1:~/Desktop/project/B26$ javac Student.java
aravind@aravind-Gateway-NE46Rs1:~/Desktop/project/B26$ java Student
I am Not completed Madam
I am can not study everday
No Way
aravind@aravind-Gateway-NE46Rs1:~/Desktop/project/B26$ javac Student.java
Student.java:16: error: cannot find symbol
hari.play();
^
symbol: method play()
location: variable hari of type Madam
1 error
reference:
Leave a comment