一、多态
1.基本知识点
Cat cat = new Cat();
Animal animal = new Cat();
关于instance Of:判断某个对象是否属于某种类型
eg:Animal cat = new Cat();
boolean flag = cat instanceof Animal; //判断cat对象是否属于Animal类型
2.多态转型
Animal animal = new Cat();// Cat转给Animal---向上转型(增强可扩展性)
Cat cat1 = (Cat) cat;// 向下转型
编译看左边,运行看右边。
案例:
package zhuan;
/**
* @Author:张金贺
* @Date:2022/6/22 21:48
* @Version 1.0
*/
public class test {
public static void main(String[] args) {
Animal cat =new Cat();
cat.eat();
//编译看左边,运行看右边。
//无法调用爬树方法,因此需要向下转型。
if(cat instanceof Cat) {
Cat cat1 = (Cat) cat;//向下转型
}else
{
System.out.println("类型不匹配");
return;
}
((Cat) cat).pashu();
}
}
二、综合案例
题目:
package waibao;
/**
* @Author:张金贺
* @Date:2022/6/22 21:58
* @Version 1.0
*/
public abstract class Employee {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Employee(String name, Integer age) {
this.name = name;
this.age = age;
}
abstract void work();
abstract double calMoney(int days);
}
package waibao;
/**
* @Author:张金贺
* @Date:2022/6/22 22:01
* @Version 1.0
*/
public class Developer extends Employee{
public Developer(String name, Integer age) {
super(name, age);
}
@Override
void work() {
System.out.println("开发项目");
}
@Override
double calMoney(int days) {
if (days<60){
return 500*days;
}
else {
return 400*days;
}
}
}
package waibao;
/**
* @Author:张金贺
* @Date:2022/6/22 22:03
* @Version 1.0
*/
public class Manager extends Employee{
public Manager(String name, Integer age) {
super(name, age);
}
@Override
void work() {
System.out.println("项目管理");
}
@Override
double calMoney(int days) {
if (days<60){
return 800*days;
}
else {
return 600*days;
}
}
}
package waibao;
/**
* @Author:张金贺
* @Date:2022/6/22 22:04
* @Version 1.0
*/
public class Test {
public static void main(String[] args) {
Employee[] employees=new Employee[3];
Developer d1=new Developer("小王",23);
Developer d2=new Developer("小李",22);
Manager m1=new Manager("老张",32);
employees[0]=d1;
employees[1]=d2;
employees[2]=m1;
double totalMoney=0;
for (Employee employee : employees) {
totalMoney+= employee.calMoney(90);
}
System.out.println("总共需要支付"+totalMoney+"元");
}
}
三、final关键字和static静态关键字
1.final关键字
被final修饰的类不可以被继承!!!
被final修饰的方法不可以被重写!!!
final修饰常量,只可以赋值一次,且值不在发生变化。
final修饰引用类型的变量注意:
package finaltest;
/**
* @Author:张金贺
* @Date:2022/6/22 22:19
* @Version 1.0
*/
public class demo2 {
final demo1 d=new demo1();
public void method(){
d.num=100;
demo1 d1=new demo1();
d=d1;//报错
}
}
final修饰的成员变量必须在对象创建之前赋值。所以要么在定义时赋值,要么在构造方法中为其赋值。
public class x {
final int num1 = 2;
final int num2;
fina1 int num3;//报错
public X(){
num2 = 4;
}
}
2.static静态关键字
对于一个public static 的属性,可以直接类名.进行赋值。(不占用堆,直接有静态块。)
3.静态方法和静态常量
静态方法只能访问静态成员。(一般定义到静态类)
public static final 修饰静态常量。