JAVA-Interface and Inheritance (9) Abstract Class

Abstract class

Add an abstract method attack for Hero, and declare Hero as abstract.
APHero, ADHero, and ADAPHero are subclasses of Hero and inherit the attributes and methods of Hero.
But their attack methods are different, so after inheriting the Hero class, these subclasses must provide different attack method implementations.

public abstract class hero implements AD{
    
    
	String name;
	int hp;
	int  movespeed = 1000;
	int armor;
	public abstract void attack(); // 抽象方法attack
    // Hero的子类会被要求实现attack方法

Abstract classes can have no abstract methods

The Hero class can be declared as an abstract class without providing an abstract method.
Once a class is declared as an abstract class, it cannot be instantiated directly.

public abstract class hero {
    
    
	public static void main(String args[]){
    
    
	hero a = new hero(); //这样会报错
	}
}

The difference between abstract class and interface

Difference 1:
Subclass can only inherit one abstract class, not multiple
subclasses can implement multiple interfaces

Difference 1:
Subclass can only inherit one abstract class, not multiple
subclasses can implement multiple interfaces
Difference 2:
Abstract class can define
public, protected, package, private
static and non-static properties
final and non-final properties
but in the interface The declared attributes can only be
public
static
final,
even if there is no explicit declaration

Note: Both abstract classes and interfaces can have entity methods. The entity method in the interface, called the default method

package charactor;
  
public interface AP {
    
    
  
    public static final int resistPhysic = 100;
     
    //resistMagic即便没有显式的声明为 public static final
    //但依然默认为public static final
    int resistMagic = 0;
     
    public void magicAttack();
}

Exercise-Abstract ⭐⭐⭐Some
items disappear after use, such as blood bottles

Some items will continue to exist after being used, such as weapons

Design an abstract method for the Item class

package charactor;

public abstract class item {
    
    
	public void effect() {
    
    
		System.out.println("使用后可以加血");
	}
	public abstract void disposable();
}
package charactor;

public class weapon extends item{
    
    

	public void disposable() {
    
    
		panduan();
	}
	public boolean panduan() {
    
    
		return false;
	}
}
package charactor;

public class armor extends item{
    
    
	public boolean pd() {
    
    
		return false;
	}
	public void disposable() {
    
    
		pd();
	}
}

Guess you like

Origin blog.csdn.net/qq_17802895/article/details/108614110