VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > Java教程 >
  • java instanceof与类型转换

instanceof与类型转换(基础篇)

instanceof可以用来判断一个对象是什么类型,判断两个类之间是否存在父子关系。

都在代码里啦

//测试类
package oop;
import oop.demo02.Person;
import oop.demo02.Student;
import oop.demo02.Teacher;
public class Application {
    public static void main(String[] args) {
        //在这四个类之间的关系
        //Object>String
        //Object>Person>Teacher
        //Object>Person>Student
        //用instanceof输出判断各类之间的关系
        //System.out.println("x instanceof y");能不能编译通过主要看x与y是不是存在父子关系。
        //结果为true还是false看x所指向的实际类型是不是y的子类型。
        Object object = new Student();
        System.out.println(object instanceof Student);//true
        System.out.println(object instanceof Person);//true
        System.out.println(object instanceof Teacher);//False
        System.out.println(object instanceof Object);//true
        System.out.println(object instanceof String);//false
        System.out.println("*******************************");
        Person person =new Student();
        System.out.println(person instanceof Student);//true
        System.out.println(person instanceof Person);//true
        System.out.println(person instanceof Teacher);//False
        System.out.println(person instanceof Object);//true
        //System.out.println(person instanceof String);//false编译时就会报错
        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 Teacher);//False//编译报错
        System.out.println(student instanceof Object);//true
    //   System.out.println(student instanceof  String);//编译报错
    }
}
//父类与子类,都继承父类
package oop.demo02;
public class Student extends Person {
}
package oop.demo02;
public class Person {
    public void run(){
        System.out.println("run");
        //在这里是无法重写子类的方法的。
    }
}
package oop.demo02;
public class Teacher  extends Person {
}

类型转换

当父类转向子类需要强制转换,向下转型

子类转向父类自动转换。,向上转型

父类的引用指向子类的对象。

代码示例:

//首先我们写一个父类
package oop.demo02;

public class Person {
    public void run(){
        System.out.println("run");
        //在这里是无法重写子类的方法的。
    }
}
//再写一个子类
package oop.demo02;
public class Student extends Person {
    public void go() {
        System.out.println("go");
    }
}//子类里面有自己的go方法和继承了父类的run方法
//写一个测试类调用
package oop;

import oop.demo02.Person;
import oop.demo02.Student;
//类型之间的转换
public class Application {
    public static void main(String[] args) {
        //父转子,要强转,子转父,不需要。
     // Person oba =  new Student();
        //把student对象类型转换为Student,就可以使用Student类型的方法了
    //Student student = (Student) oba;//进行强制转换。
  //  student.go();
   Student student = new Student();
   student.go();
   Person person = student;//低转高
    }
}



出处:https://www.cnblogs.com/kuangsun125/p/15103515.html


相关教程