Abstract class: Use the keyword abstract; if a class is modified by abstract, it is called an abstract class.
If abstract modifies a method, then this method is called an abstract method
If abstract modifies a class, then this class is called an abstract class.
If a class inherits an abstract class, it must implement the abstract method in the abstract class.
Usage of abstract keyword:
Method body: The content of the curly brackets in the method is the method body.
1. If a method does not have a method body, then the method must be modified with abstract.
2. If there is an abstract method in a class, then the class must be modified with abstract, which is an abstract class.
3. If a non-abstract class inherits this abstract class, then all abstract methods must be rewritten in this non-abstract class.
4. An abstract class can have non-abstract methods.
5. Constructors can exist in an abstract class. The function is to allow subclasses to initialize variables in the parent class.
6. Abstract classes cannot create objects
Reason: If you create an object, the object can call the abstract method, so it is meaningless to call the abstract method.
7. Abstract methods do not need to appear in an abstract class.
Usage scenarios of the abstract keyword:
When we describe a thing, we find that the thing does have a certain behavior, but this behavior is not specific. Then at this time, we can extract this behavior and declare an unimplemented behavior. , this behavior is called abstract behavior, so you need to use abstract classes at this time.
//The class modified by the abstract keyword is called an abstract class.
abstract class Animal
{
String name;
String color;
abstract public void run ();//Abstract method has no body and no concrete implementation of the method.
public void eat (){
System.out.println("Animals are eating");
}
}
//A non-abstract class inherits an abstract class and must implement all methods in the abstract class .
class Dog extends Animal
{
//You need to override the run method in the parent class
public void run(){
System.out.println(name + "Run fast");
}
}
class Fish extends Animal
{
//Rewrite method: There is no mandatory requirement to override the run method.
//Should be rewritten, but I can do without. This can easily lead to problems.
//Think of a way to force the subclass to override a certain method in the parent class
public void run(){
System.out.println(name+"swim fast");
}
}
class Demo8
{
public static void main(String[] args)
{
Dog d = new Dog();
d.name = "Caucasus";
d.run();
d.eat() ;
Fish fish = new Fish();
fish.name = "Whale";
fish.run();
fish.eat();
}
}