Java 5-4 abstract类与方法

abstract类与方法

1.抽象类:

    用abstract修饰符修饰的类为抽象类,修饰的方法为抽象方法。 用abstract修饰的方法只能声明不能实现。且final和abstract不能同时修饰一个方法 例如:
abstract class A{
          
   
abstract int min (int x,int y);//只声明不实现
}

2.抽象类特点:

    抽象类中可以有抽象类方法,也可以有非抽象类方法。而普通类中不能有抽象类方法 抽象类中可以全为非抽象方法,可以没有抽象方法 abstract类不能使用new运算符创建对象 非抽象类继承了某个抽象类:则其必须去掉abstract修饰符,重写父类的抽象方法,给出具体的方法体 抽象类继承了某个抽象类:则其可以重写父类abstract类方法,也可以继承父类的abstract方法。 抽象类声明的对象可以成为其子类对象的上转型对象,调用子类重写的方法

例子:定义一个机动车抽象类,该类中有启动,加速,刹车三种功能,分别用手动挡,自动挡实现机动车的功能细节

abstract class 机动车{
          
   
abstract void 启动();
abstract void 加速();
abstract void 刹车();
}
class 手动挡汽车 extends 机动车{
          
   
void 启动(){
          
   
System.out.println("踏下离合器,换到一档");
}
void 加速(){
          
   
System.out.println("换到高档,踩油门");
}
void 刹车(){
          
   
System.out.println("踏下离合器和刹车,将档位换到一档");
}
}
class 自动挡汽车 extends 机动车{
          
   
void 启动(){
          
   
System.out.println("使用前进档");
}
void 加速(){
          
   
System.out.println("踩油门");
}
void 刹车(){
          
   
System.out.println("踩刹车");
}
}

public class example_1{
          
   
public class void main(String args[ ]){
          
   
机动车 car=new 手动挡汽车();
System.out.println("手动挡汽车的具体操作是:");
car.启动();
car.加速();
car.刹车();
car=new 自动挡汽车();
System.out.println("自动挡汽车的具体操作是:");
car.启动();
car.加速();
car.刹车();
}
}

3.多态设计 例子:设计一个动物声音模拟器,模拟器可以模拟多种动物的叫声

package d;

abstract class Animal {
          
   
	abstract void cry();
	abstract String getAnimalName();
}

class Dog extends Animal{
          
   
	void cry() {
          
   
		System.out.println("wuwuwuwwuu");
	}
	
	String getAnimalName() {
          
   
		return "狗";
	}	
}

class Cat extends Animal{
          
   
	 void cry() {
          
   
			System.out.println("miaomiao");
		}
	
		String getAnimalName() {
          
   
			return "猫";
		}
 }
 
class 动物声音模拟器{
          
   
	public void palySound(Animal animal)
	{
          
   
		System.out.println("现在播放"+animal.getAnimalName()+"类的声音");
		animal.cry();
	} 
 }

public class example_3 {
          
   

	public static void main(String[] args) {
          
   
		        动物声音模拟器 模拟器=new 动物声音模拟器();
		        Animal animal=new Dog();
				模拟器.palySound(animal);
				animal=new Cat();
				模拟器.palySound(animal);			
			}

	}
经验分享 程序员 微信小程序 职场和发展