首页 > 其他分享 >打卡第十四天!!(明天去看电影)

打卡第十四天!!(明天去看电影)

时间:2024-07-18 22:30:30浏览次数:8  
标签:instanceof 子类 电影 System 第十四天 Student println 打卡 out

重写

  • 重写都是方法的重写,和属性无关

  • 父类的引用指向了子类

  • 方法的调用之和定义的数据类型有关(左边)

  • 静态的方法和非静态方法区别很大

  • 1.有static时,b调用了B类的方法,因为b是用B类定义的

  • 2.没有static是,b调用的是对象的方法,而b使用A类new的

A a = new A();
a.test();
​
B b = new A();
b.test();

Alt+Inster ---> Override Methods(重写方法)

/*
重写:需要有继承关系,子类重写父类的方法
1.方法名必须相同
2.参数列表必须相同
3.修饰符:范围可以扩大   public>protected>Default>private
4.抛出的异常:范围可以被缩小,但不能扩大    ClassNotFoundException  --->Exception(范围非常大)
​
重写,子类的方法和符类必须一致,:方法体不同!
​
为什么需要重写:
1.父类的功能:子类不一定需要,或者不一定满足!
*/

多态

  • 及同一方法可以根据发送对象的不同而采用多种不同的行为方法

注意事项:

  • 多态是方法的多态,属性没有多态

  • 父类和子类,有联系 类型转换异常! ClassCastException

  • 存在条件:继承关系,方法需要重写 父类引用指向子类对象

package oop;
​
​
import oop.Demo06.Person;
import oop.Demo06.Student;
​
public class Application {
    public static void main(String[] args) {
​
        //一个对象的实际类型是确定的
        //new Student();
        //new Person();
​
        //可以指向的引用类型就不确定了:父类的引用指向子类
        Student s1 = new Student();//Student能调用的方法,都是自己的或者继承父类的
        //Person 父类型,可以指向子类,但不能调用子类独有的方法
        Person s2 = new Student();//父类引用
        Object s3 = new Student();
​
​
        //对象能执行哪些方法,主要看左边的类型
        ((Student)s2).eat();//-----强制转换-----
        //s2.eat();//子类重写了父类的方法,执行子类的方法
        s1.eat();
    }
}
​

package oop.Demo06;
​
public class Student extends Person{
    @Override
    public void run(){
        System.out.println("son");
​
    }
​
    public void eat(){
        System.out.println("eat");
    }
​
}
​

package oop.Demo06;
​
public class Person {
    public void run(){
        System.out.println("run");
    }
}

instanceof和强制转换

类型之间的转化:

基本类型的转化: 父 子

/*
1.父类引用指向子类的对象
2.把子类转换为父类,向上转型
3.把父类转换为子类,向下转换:强制转换
4。方便方法的调用,减少重复的代码!
​
抽象:   封装、继承、多态  ----->抽象类、接口。。。。
*/

instanceof

package oop;
​
​
import oop.Demo06.Person;
import oop.Demo06.Student;
import oop.Demo06.Teacher;
​
public class Application {
    public static void main(String[] args) {
​
        //Object>Person>Student
        //Object>Person>Teacher
        //Object>String
        Object object = new Student();
​
        System.out.println(object instanceof Student);
        System.out.println(object instanceof Person);
        System.out.println(object instanceof Object);
        System.out.println(object instanceof Teacher);
        System.out.println(object instanceof String);
​
        System.out.println("============================");
​
        Person person = new Student();
​
        System.out.println(person instanceof Student);
        System.out.println(person instanceof Person);
        System.out.println(person instanceof Object);
        System.out.println(person instanceof Teacher);
        //System.out.println(person instanceof String);//报错
​
​
​
    }
}

标签:instanceof,子类,电影,System,第十四天,Student,println,打卡,out
From: https://blog.csdn.net/wdchun__/article/details/140534765

相关文章