Java笔记:abstract关键字的使用

/*
 * abstract关键字的使用
 * 1.abstract:抽象的
 * 2.abstract可以用来修饰的结构:类、方法
 * 
 * 3.abstract修饰类:抽象类
 * 		此类不能实例化
 * 		抽象类中一定有构造器,便于子类实例化时调用,只要是类就有构造器
 * 		开发中,都会提供抽象类的子类,让子类对象实例化,完成相关的操作
 * 
 * 
 * 4.abstract修饰方法:抽象方法
 * 		抽象方法只有方法的声明,没有方法体
 * 		包含抽象方法的类,一定是一个抽象类。反之,抽象类中可以没有抽象方法的。
 * 		若子类重写了父类中的所有的抽象方法,则子类方可实例化
 * 		若子类没有重写服了中的所有的抽象方法,则此子类也是一个抽象类,需要使用abstract修饰类
 * 
 * 5.abstract使用上的注意点:
 * 		1.abstract不能用来修饰:属性、构造器等结构
 * 		2.abstract不能用来修饰私有方法、静态方法、final的方法
 * 
 */

public class AbstractTest {
    
    

	public static void main(String[] args) {
    
    
		//一旦Person类抽象了,就不可实例化
//		Person p1 = new Person();
//		p1.eat();
	}
}


abstract class Creature{
    
    
	public abstract void breath();
}


abstract class Person extends Creature{
    
    
	String name;
	int age;
	
	public Person() {
    
    
		
	}
	public Person(String name,int age	) {
    
    
		this.name = name;
		this.age = age;
	}
	
//	public void eat() {
    
    
//		System.out.println("人吃饭");
//	}
	
	//抽象方法
	public abstract void eat();
	
	public void walk() {
    
    
		System.out.println("人走路");
	}
}

class Student extends Person{
    
    
	
	public Student(String name,int age) {
    
    
		super(name,age);
	}
	
	public void eat() {
    
    
		System.out.println("学生多吃有营养的事物");
	}

	@Override
	public void breath() {
    
    
		System.out.println("学生应该呼吸新鲜的空气");
		
	}
	
}
public abstract class Employee {
    
    

	private String name;
	private int id;
	private double salary;
	public Employee() {
    
    
		super();
	}
	public Employee(String name, int id, double salary) {
    
    
		super();
		this.name = name;
		this.id = id;
		this.salary = salary;
	}
	
	public abstract void work();
}
public class Manager extends Employee{
    
    

	private double bonus;//奖金
	
	
	public Manager(double bonus) {
    
    
		super();
		this.bonus = bonus;
	}


	public Manager(String name, int id, double salary, double bonus) {
    
    
		super(name, id, salary);
		this.bonus = bonus;
	}





	@Override
	public void work() {
    
    
		System.out.println("管理员工,提高公司运行效率");
		
	}

}

public class CommonEmployee extends Employee {
    
    

	@Override
	public void work() {
    
    
		System.out.println("员工在一线车间生产产品");

	}

}

public class EmployeeTest {
    
    

	public static void main(String[] args) {
    
    
		
		//多态
		Employee manager = new Manager("库克",1001,5000,500000);
		//Manager manager = new Manager("库克",1001,5000,500000);
		
		manager.work();
		
		CommonEmployee commonEmployee = new CommonEmployee();
		commonEmployee.work();
	}
}

Guess you like

Origin blog.csdn.net/weixin_44201223/article/details/118442471