java面向对象 09 instanceof 和类型转换

     instanceof和类型转换

判断一个类对象是什么类型

 

package demo04;

public class Perosn
{
}

package demo04;

public class Student extends Perosn
{
 
}


package demo04;

public class Teacher extends Perosn
{
}

 

package demo04;

public class Application
{
   public static void main(String[] args)
  {
 
   //object>person>Teacher
   //object>person>student
   // System.out.println(x instanceof y); 能不能编译通过!取决于x和y有没有父子关系和有没有关系 还有x指向的实际类型是y的子类型才为true
   Object object=new Student();
       System.out.println(object instanceof Student);//true
       System.out.println(object instanceof Perosn);//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("-------------------");
   Perosn perosn=new Student();
       System.out.println(perosn instanceof Student);//true
       System.out.println(perosn instanceof Perosn);//true
       System.out.println(perosn instanceof Object);//true
       System.out.println(perosn instanceof Teacher);//false
   //System.out.println(perosn instanceof String);//编译报错
       System.out.println("-------------------------");
   Student student=new Student();
       System.out.println(student instanceof Student);//true
     System.out.println(student instanceof Perosn);//true
       System.out.println(student instanceof Object);//true
   //System.out.println(student instanceof Teacher);//编译报错
   //System.out.println(perosn instanceof String);//编译报错
 
}
}

 

类的类型转换

package demo04;

public class Perosn {
}



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

 

package demo04;

public class Application
{
   public static void main(String[] args)
  {

   //类型之间的转换:父 子
       //高                 低
       Perosn obj1=new Student();
       //student 将这个对象转换为Student类型,我们就可以使用Student类型的方法了!
       Student student=(Student) obj1;
       student.go();
      // (((Student)obj1).go());
       //子类转换为父类,可能丢失自己的本来的一些方法!
     //Student student=new Student();
     //student.go();
   // Perosn perosn=student;f
       
       
       /*
1.父类引用指向子类的对象
2.把子类转换为父类,向上转型;
3.把父类类型转换为子类,向下转型;强制转换
4.方便方法的调用,减少重复的代码!简介
抽象:封装,继承,多态!
*/

 
posted @ 2022-04-23 17:50  zjw_rp  阅读(11)  评论(0)    收藏  举报