第六周学习总结
一、多态
(一)多态的定义
(二)调用成员变量
1 public class Test{
2 public static void main(String[] args) {
3 Animal a = new Dog();
4 System.out.println(a.name);
5 }
6 }
7 class Animal{
8 String name = "动物";
9
10 public void show(){
11 System.out.println("Animal --- show方法");
12 }
13 {
14
15 class Dog extends Animal{
16 String name = "狗";
17 @override
18
19 public void show() {
20 System.out.println("Dog --- show方法);
21 }
22 }
(三) 优势,弊端
1 public class Test {
2 public static void main(String[] args){
3 Animala = new Dog();
4 //编译看左边,运行看右边
5 a.eat();
6 /多态的弊端
7 //不能调用了类的特有功能
8 //报错的原因?
9 //当调用成员方法的时候,编译看左边,运行看右边
10 //那么在编译的时候会先检查左边的父类中有没有这个方法,如果没有直接报错。
11 //a.lookHome();
12 //解决方案:
13 //变回子类类型就可以了
14 //细节:转换的时候不能瞎转,如果转成其他类的类型 就会报错
15 //Dog c= (Dog)a;
16 //c.clookHome();
17 //新特性
18 //先判断a是否为Dog类型,如果是,则强转成Dog类型,转换之后变量名为d
19 //如果不是,则不强转,结果直接是false
20 if(a instanceof Dog d){
21 d.lookHome();
22 }else if(a instanceofCatc){
23 c.catchMouse();
24 }elsef{
25 System.out.println("没有这个类型,无法转换");
26 }
27 }
28 }
29
30 class Animal {
31 public void eat(){
32 System.out.println("动物在吃东西");
33 }
34 }
35
36 class Dog extends Animal{
37 @Override
38 public void eat(){
39 System.out.println("狗吃骨头");
40 }
41 public void lookHome(){
42 System.out.print1n("狗看家");
43 }
44 }
45
46 class Cat extends Animal{
47 @Override
48 public void eat(){
49 System.out.println("猫吃小鱼干”);
50 }
51 publicvoidcatchMouse(){
52 System.out.println("犹抓老叫");
53 }
54 }
二、包
1 import com.itheima.Student;
2 public class Test {
3 public static void main(String[] args) {
4 Student s = new Student();
5 }
6 }
三、final
1 1.final void show() 2 { 3 System.out.println.("父类的show方法"); 4 } 5 } 6 7 2.final class fu{ 8 } 9 10 3.final int a = 10; 11
12 4. final int[] ARR = {1,2,3};
13 ARR[0] = 10 ; // 可以
14 ARR = new int [100] ; //不可以
四、权限修饰符
五、抽象类
(一)定义
(二)练习
1 public abstrac class Anima{
2 private String name;
3 private int age;
4 public Animal(){
5 public Animal(String name, int age) {
6 this.name = name;
7 this.age = age;
8 }
9 }
10 public String getname(){
11 return name ;
12 }
13 public void setName(String name){
14 this.name = name;
15 }
16 public int getAge() {
17 return age;
18 }
19 publicvoidsetAce(int age)
20 this.age =age
21 }
22 public void drink(){
23 System,out.println 动物在喝水");
24 }
25 public abstract void cat();
26 }
27 }
public class Frog extends Animal{
public Frog{}
public Fros(String name, int age) {
super(name, age);
}
@0verride
public void eat() {
System.out.println("青蛙在吃虫子");
}
}
public class Dog extends Animal{
public Dos{}
public Dog(String name,int age){
super(name, age);
}
@Overrsda
public void eat() {
System.out.println("狗吃骨头”);
}
}
public class Sheep extendsAnimal{
public Sheep{}
public Sheep(String name, int age){
super(name,age);
}
@Overade
public void eat() {
System.out.orint1n("山羊在吃草");
}
}
public classTest {
public static void main(String[] args){
//创建对象
Frog f = new Frog( name:"小绿",age:1);
System.out.print1n(f.getName()+",”+ f.getAge());
f.drink();
f.eat();
}
六、接口
下周学习 :内部类,接口细节