基本数据类型转换
自动类型转换:把小类型的数组赋给大类型的变量(此时的大和小表示容量范围)
byte b =12 ; //byte是1个字节
int i = b; // int 是4个字节
强制类型转换:把大类型的数据赋给小类型的变量。
int i =12; // int是4个字节
short s = (short) i // short 是2个字节
引用类型的转换
引用类型的大和小,指的是父类和子类的关系
自动类型转换:把子类对象赋值给父类变量(多态)
Animal a = new Dog();
// Object是所有类的根类;
Object obj = new Dog();
强制类型转换:把父类类型对象赋给子类类型变量(但是父类类型变量的真实类型应该是子类类型)
Animal a = new Dog();
Dog d = (Dog) a;
instanceof 运算符
语法格式:对象A instanceof 对象B;
若对象时类的实例返回true,
若对象时类的父类的实例也返回true;
class InstanceOfDemo
{
public static void main(String[] args)
{
Objectobj = "ABC"; // 多态,String对象赋值给Objectobj对象
System.out.println(obj instanceof Object);
System.out.println(obj instanceof String);
}
}
---------- 运行java ----------
true
true
输出完成 (耗时 0 秒) - 正常终止
在开发中,有时候,我们只想判断是真实类型的实例,而不想判断为编译类型的实例,需要使用getClass方法,它获取的是对象的真实类型。如下代码:
class InstanceOfDemo
{
public static void main(String[] args)
{
Object obj = "ABC";
System.out.println(obj.getClass()); //获取对象的真实类型
System.out.println(obj.getClass() == Object.class); // false
System.out.println(obj.getClass() == String.class); // true
}
}
---------- 运行java ----------
class java.lang.String
false
true
输出完成 (耗时 0 秒) - 正常终止
下面举个例子总结一下这篇博客的知识:
class Person
{
public void feed(Animal a){
a.eat();
if (a.getClass() == Dog.class)
{
a.sleep();
}
else if (a.getClass() == Cat.class)
{
a.catchMouse();
}
}
}
class Animal
{
public void eat(){
System.out.println("喂食.....");
}
public void sleep(){}; // 有点像接口的意思了
public void catchMouse(){}; //有点像接口的意思了
}
class Dog extends Animal
{
public void eat(){
System.out.println("吃骨头中......");
}
public void sleep(){
System.out.println("吃完了骨头,乖乖地睡着了......");
}
}
class Cat extends Animal
{
public void eat(){
System.out.println("吃鱼中......");
}
public void catchMouse(){
System.out.println("吃完了鱼,去逮老鼠了......");
}
}
class InstanceOfDemo
{
public static void main(String[] args)
{
Person p = new Person();
Animal a = new Dog();
Animal c = new Cat();
p.feed(a);
p.feed(c);
}
}
---------- 运行java ----------
吃骨头中......
吃完了骨头,乖乖地睡着了......
吃鱼中......
吃完了鱼,去逮老鼠了......
输出完成 (耗时 0 秒) - 正常终止
或者person类中可以使用强制类型转换:
class Person
{
public void feed(Animal a){
a.eat();
if (a.getClass() == Dog.class)
{
Dog d = (Dog) a;
d.sleep();
}
else if (a.getClass() == Cat.class)
{
Cat c = (Cat) a ;
c.catchMouse();
}
}
}
但是,这样写的话,就不用再Animal类中定义sleep方法和catchMouse方法:
之所在一开始第一种代码中的Animal类定义这两个方式,我们没有使用强制转换,在编译的时候,有先去Animal类中寻找sleep方法和catchMouse方法,找不到就编译报错。
class Animal
{
public void eat(){
System.out.println("喂食.....");
}
}