Day 24 : Abstraction

Chi-Tse Chiang
2022-10-09 23:48:34

Intro

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.

Abstract Classes and Functions

*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?

The abstract function in the abstract class cannot be defined initially (fast() is a general function)

-> Usually, we override it by inheriting from its child class.

To access the abstract function in the class, we also implement it through the concept of inheritance.

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

Abstract Inheritance

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.

Finally, let's summarize the content shared above:

1. Abstract classes cannot create objects

2. Abstract functions do not define initial content

3. Access the content of abstract functions through the concept of inheritance

4. When using abstract functions, pay attention to the use of access modifiers

Example

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.