1.抽象类
(1)一个抽象类可以没有抽象方法,但定义了抽象方法的类必须在类头使用absrtact关键字
(2)类继承了抽象类就要实现抽象类中所有的抽象方法
(3)抽象类不能被实例化
2.抽象方法
(1)抽象方法可以使用public,protected,但是不能使用final,private和static
练习
1.练习使用抽象类和抽象方法
package Test1;
public abstract class Animal {
public abstract void predation();
public void eat() {
this.predation();
}
}
package Test1;
public class Monkey extends Animal {
public void predation() {
System.out.println("猴子吃香蕉");
}
}
package Test1;
public class Tiger extends Animal {
public void predation() {
System.out.println("老虎吃肉");
}
}
package Test1;
public class Wolf extends Animal {
public void predation() {
System.out.println("白狼找女儿");
}
}
package Test1;
public class Test {
public static void main(String[] args) {
Animal wolf = new Wolf();
Animal tiger = new Tiger();
Animal monkey = new Monkey();
wolf.eat();
tiger.eat();
monkey.eat();
}
}
2.练习使用抽象类和抽象方法
package Test2;
public abstract class Company {
String name;
String id;
double salay;
public Company(String name, String id, double salay) {
this.name = name;
this.id = id;
this.salay = salay;
}
public abstract void Work();
public abstract void show();
}
package Test2;
public class Programmer extends Company {
public Programmer(String name, String id, double salay) {
super(name, id, salay);
}
public void Work() {
System.out.println("工作:程序员,码代码的");
}
public void show() {
System.out.printf("姓名:%s\t编号:%s\t工资:%.2f\n", name, id, salay);
this.Work();
}
}
package Test2;
public class PM extends Company {
double pmsalay;
public PM(String name, String id, double salay, double pmsalay) {
super(name, id, salay);
this.pmsalay = pmsalay;
}
public void Work() {
System.out.println("工作:管理");
}
public void show() {
System.out.printf("姓名:%s\t编号:%s\t工资:%.2f\t奖金:%.2f\n", name, id, salay, pmsalay);
this.Work();
}
}
package Test2;
package Test2;
public class Test2 {
public static void main(String[] args) {
Company pm = new PM("增项为", "13216464X", 1000000, 100000000);
Company pr = new Programmer("因力争", "6546416541ez", 500);
pm.show();
pr.show();
}
}
运行结果:
个人总结:
1.概念没弄清
2.多练多记
3.提前预习