abstract class

 

Definition grammar

usage restrictions

Ordinary classes can directly generate instantiated objects, and in ordinary classes

 

The difference of having an abstract class is just having an abstract declaration

The principles of using abstract classes are as follows:

Abstract classes must have subclasses, that is: each abstract class must be inherited by subclasses

Subclasses of abstract classes (subclasses are not abstract classes) must override all abstract methods in the abstract class

 

Summarize:

1. There will be clear method overriding requirements in the abstract class inheritance subclass, while the ordinary class does not

2. An abstract class only defines some more abstract methods than an ordinary class, and the other components are exactly the same as the ordinary class.

3. Ordinary class objects can be instantiated directly, but abstract class objects must be up-cast before they can be instantiated

 

 

usage restrictions

Since there are some properties in the abstract class, there must be a constructor in the abstract class.

 

 

abstract class Action
{
public static final int EAT=1;
public static final int SLEEP=3;
public static final int WORK=5;
public void command(int flag)
{
switch(flag){
case EAT:
this.eat();
break;
case SLEEP:
this.sleep();
break;
case WORK:
this.work();
break;
}
}
public abstract void eat();
public abstract void sleep();
public abstract void work();
}
class Robot extends Action
{
public void eat(){
System.out.println("吃!");
}
public void sleep(){
}
public void work(){
System.out.println("工作!");
}

}
class Human extends Action
{
public void eat(){
System.out.println("吃!");
}
public void sleep(){
System.out.println("睡!");
}
public void work(){
System.out.println("工作!");
}

}
class Pig extends Action
{
public void eat(){
System.out.println("吃!");
}
public void sleep(){
System.out.println("睡!");
}
public void work(){
}

}
public class Abstracttest
{
public static void main(String args[]){
fun(new Robot());
fun(new Human());
fun(new Pig());
}
public static void fun(Action act){
act.command(Action.EAT);
act.command(Action.SLEEP);
act.command(Action.WORK);
}
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324611883&siteId=291194637