如何在Java中向上转型和向下转型同一个对象?
在Java中,将一种数据类型转换为另一种数据类型被称为类型转换。
向上转型 − 将更高数据类型转换为较低数据类型,称为缩小转换(将更高数据类型的值赋给较低数据类型变量)。
示例
import java.util.Scanner;
public class NarrowingExample {
public static void main(String args[]){
char ch = (char) 67;
System.out.println("Character value of the given integer: "+ch);
}
}输出
Character value of the given integer: C
向下转型 − 将较低数据类型转换为更高数据类型,称为扩展转换(将较低数据类型的值赋给更高数据类型变量)。
示例
public class WideningExample {
public static void main(String args[]){
char ch = 'C';
int i = ch;
System.out.println(i);
}
}输出
Integer value of the given character: 67
向上转型和向下转型同一个对象
类似地,您还可以将一个类类型的对象转换为其他类类型。但这两个类应该具有继承关系。然后,
如果您将父类转换为子类类型,则在引用方面称为缩小转换(子类引用变量持有父类对象)。
Sub sub = (Sub)new Super();
如果您将子类转换为父类类型,则在引用方面称为扩展转换(父类引用变量持有子类对象)。
Super sup = new Sub();
示例
以下Java程序演示了如何向上转型和向下转型同一个对象。
class Person{
public String name;
public int age;
Person(){}
public Person(String name, int age){
this.name = name;
this.age = age;
}
public void displayPerson() {
System.out.println("Data of the Person class: ");
System.out.println("Name: "+this.name);
System.out.println("Age: "+this.age);
}
}
public class Student extends Person {
public String branch;
public int Student_id;
Student(){}
public Student(String name, int age, String branch, int Student_id){
super(name, age);
this.branch = branch;
this.Student_id = Student_id;
}
public void displayStudent() {
System.out.println("Data of the Student class: ");
System.out.println("Name: "+super.name);
System.out.println("Age: "+super.age);
System.out.println("Branch: "+this.branch);
System.out.println("Student ID: "+this.Student_id);
}
public static void main(String[] args) {
Person person = new Person();
Student student = new Student("Krishna", 20, "IT", 1256);
//Up casting
person = student;
person.displayPerson(); //only super class methods
//Down casting
student = (Student) person;
student.displayPerson();
student.displayStudent();
}
}输出
Data of the Person class: Name: Krishna Age: 20 Data of the Person class: Name: Krishna Age: 20 Data of the Student class: Name: Krishna Age: 20 Branch: IT Student ID: 1256
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP