zoukankan      html  css  js  c++  java
  • 面向对象13instanceof和类型转换

    package com.oop;

    import com.oop.demo06.Person;
    import com.oop.demo06.Student;
    import com.oop.demo06.Teacher;

    public class Application {
    public static void main(String[] args) {
    //类型之间的转换:父 子
    //
    // //高 //底
    // Person obj = new Student();
    //
    // //student将这个对象转换为Studnet类型,我们就可以使用Student类型的方法了!
    //
    // Student student = (Student) obj;
    // student.go();

    //子类转换为夫父类,可能对视自己的本来的一些方法!
    Student student = new Student();
    student.go();
    Person person = student;


    }

    }

    /*
    1.父类引用指向子类的对象
    2.把子类转换为父类,向上转型;
    3.把父类转换为子类,向下转型;强制转换,
    4.方便方法的调用,减少重复的代码!简介

    抽象:封装、继承、多态! 抽象类,接口
    */


    package com.oop.demo06;

    public class Person {

    public void run(){
    System.out.println("run");
    }
    }

    /*
    多态注意事项:
    1.多态是方法的多态,属性没有多态
    2.父类和子类,有联系 类型转换异常!ClassCastException!
    3.存在条件:继承关系,方法需要重写,父类引用指向子类对象! Father f1 = new Son();

    1.static 方法,属于类,它不属于实例
    2.final 常量;
    3.private方法;
    */


    package com.oop.demo06;

    public class Student extends Person{
    public void go(){
    System.out.println("go");
    }

    }

    /*
    //Object > String
    //Object > Person > Teacher
    //Object > Person > Student
    Object object = new Student();

    //System.out.println(X instanceof Y);//能不能编译通过!是看XY之间有没有父子之间的关系。

    System.out.println(object instanceof Student);//true
    System.out.println(object instanceof Person);//true
    System.out.println(object instanceof Object);//true
    System.out.println(object instanceof Teacher);//false
    System.out.println(object instanceof String);//false
    System.out.println("=================");
    Person person = new Person();
    System.out.println(person instanceof Student);//true
    System.out.println(person instanceof Person);//true
    System.out.println(person instanceof Object);//true
    System.out.println(person instanceof Teacher);//false
    //System.out.println(person instanceof String);//编译报错!
    System.out.println("=================");
    Student student = new Student();
    System.out.println(student instanceof Student);//true
    System.out.println(student instanceof Person);//true
    System.out.println(student instanceof Object);//true
    //System.out.println(student instanceof Teacher);//编译报错!
    //System.out.println(student instanceof String);//编译报错!
    */


    package com.oop.demo06;

    public class Teacher extends Person{
    }
  • 相关阅读:
    PowerDesigner导出SQL脚本
    【Android进阶学习】shape和selector的结合使用(转)
    国内最新安卓渠道列表42个(转)
    安卓新框架
    通知和消息有什么区别?(转)
    XSS之xssprotect(转)
    为你的Android App实现自签名的 SSL 证书(转)
    HTTPS和HTTP的区别(转)
    IT软件技术人员的职位路线(从程序员到技术总监)
    听大神说:https和http有何区别?(转)
  • 原文地址:https://www.cnblogs.com/yuanzhihui/p/14878535.html
Copyright © 2011-2022 走看看