Previously, we introduced the concept of packaging, which is similar to the “abstract” concept shared today.
The purpose of both is to “hide information” and protect specific data!
Next, I will break down abstraction into several parts and explain them individually.
*When it comes to abstract classes, the most important thing to note is that they cannot be used to create objects.
abstract class Car{
protected long price_cost = 1000000;
public String car_brand = "Mercedes";
public void fast(){
System.out.println("300 km/h");
}
public abstract void type(String brand);
}
Abstract abstract
is a modifier of non-access permission. When declaring, we use the same method of “modifier + class + class name”
to observe the program. We can find that we only declare the content in fast()
. Why don't we declare the content of the abstract class together?
fast()
is a general function)-> Usually, we override it by inheriting from its child class.
-> And because we need to be inherited by the child class, the access modifier has certain restrictions:
The prefix modifier of the abstract function cannot be default or private
class information extends Car{
public int modelYear = 2022;
public abstract void type(String brand){
System.out.println(brand + " : " + "GLC SUV");
}
}
In this program, the contents of the abstract function are declared.
When we need to use the contents of this part in the main program, we can create an object to use it.
abstract class Car{
protected long price_cost = 1000000;
public String car_brand ;
public void fast(){
System.out.println("300 km/h");
}
public abstract void type(); //abstract method
}
class information extends Car{
information(String brand){
super.car_brand = brand;
}
public int modelYear = 2022;
public abstract void type(){
System.out.println(brand + " : " + "GLC SUV"); // the abstract method body
}
}
class Main {
public static void main(String[] args) {
information new_obj = new information("Mercedes");
new_obj.type(); // Outputs -> Mercedes : GLC SUV
}
}
Abstract classes are used for inheritance; abstract functions are used for overriding.