0
点赞
收藏
分享

微信扫一扫

Java基础--- 转型 Casting

一叶轻舟okok 2022-04-30 阅读 40
javajava-ee

Java基础--- 转型 Casting

基础类型转型

自动类型转换

强制类型转换

引用类型转型

Upcastig and Implicitly Casting

Example 1

public class Fruit {
	public void type() {
		System.out.println("This is fruit");
	}
}
public class Apple extends Fruit {
	public void type() {
		System.out.println("This is Apple");
	}
	
	public void appleJuice() {
		System.out.println("Apple Juice");
	}
}
public class Peach extends Fruit{
	public void type() {
		System.out.println("This is peach");
	}
	
	public void peachJuice() {
		System.out.println("Peach Juice");
	}
	
	public static void displayType(Fruit o) {	
		if(o instanceof Peach) {
			((Peach) o).peachJuice();
		}
		else if(o instanceof Apple) {
			((Apple) o).appleJuice();
		}
	}
	
	public static void main(String[] args) {
		Fruit f1 = new Peach();
		Fruit p1 = new Apple();
		o1.type();
		o2.type();
		//o1.peachJuice; Error
		//o2.appleJuice; Error
	}

}

Example 2

public class Fruit {
	public void type() {
		System.out.println("This is fruit");
	}
}
public class Apple extends Fruit {
	public void type() {
		System.out.println("This is Apple");
	}
	
	public void appleJuice() {
		System.out.println("Apple Juice");
	}
}
public class Peach extends Fruit{
	public void type() {
		System.out.println("This is peach");
	}
	
	public void peachJuice() {
		System.out.println("Peach Juice");
	}
	
	public static void displayType(Fruit o) {	
		if(o instanceof Peach) {
			((Peach) o).peachJuice();
		}
		else if(o instanceof Apple) {
			((Apple) o).appleJuice();
		}
	}
	
	public static void main(String[] args) {
		Fruit f1 = new Fruit();
		Fruit p1 = new Peach();
		
		//check memory address:
		System.out.println("before casting: f1 address is " + f1.toString());
		System.out.println("before casting: p1 address is " + p1.toString());
		
		
		f1 = p1; //upcasting
		//after casting the decalred type of f1 is Fruit, and the actual type is peach
	
		
		//check memory address:
		System.out.println("after casting: f1 address is " + f1.toString());
		System.out.println("after casting: p1 address is " + p1.toString());
		
		
		System.out.println("check what methods that f1 can use: ");
		f1.type(); 
		//f1.peachJuice(); Error
		
		System.out.println("check what methods that f1 can use: ");
		p1.type();
		//p1.peachJuice();
	}

}

在这里插入图片描述

Downcasting and Explicitly Casting

  • downcast的类型要遵循object的实际类型 (Example1)
  • 所以在downcasting之前, 必须判断被转型的类是子类的instance(, 用instance of关键字

Example 1:
在这里插入图片描述
在这里插入图片描述

Upcasting和downcasting的实际作用 ----- 实现多态

Notes

Casting不会创建一个新的变量
在这里插入图片描述

java根据变量的声明类型判断类型是否一致

在这里插入图片描述
在这里插入图片描述

举报

相关推荐

0 条评论