解释 Java 中对象扩展。


Java 提供各种数据类型来存储各种数据值。它提供了 7 种基本数据类型(存储单个值),即 boolean、byte、char、short、int、long、float、double,以及引用数据类型(数组和对象)。

类型转换/类型转换 - 将一种基本数据类型转换为另一种称为 Java 中的类型转换(类型转换)。您可以通过两种方式转换基本数据类型,即扩展和缩减。

扩展 - 将较低数据类型转换为较高数据类型称为扩展。在这种情况下,转换是自动完成的,因此称为隐式类型转换。在这种情况下,两种数据类型都应相互兼容。

示例

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

对象扩展

您可以将一个(类)类型的引用(对象)转换为另一个。但是,两个类之一应继承另一个。

因此,如果一个类继承了另一个类的属性,则子类对象到超类类型的转换被认为是关于对象的扩展。

示例

在以下 Java 示例中,我们有两个类,即 Person 和 Student。Person 类有两个实例变量 name 和 age,以及一个实例方法 displayPerson(),它显示 name 和 age。

Student 扩展了 Person 类,除了继承的 name 和 age 之外,它还有两个变量 branch 和 student_id。它有一个方法 displayData(),它显示所有四个值。

在 main 方法中,分别创建了两个类的对象,并且超类对象被转换为子类对象。

class Person{
   private String name;
   private int age;
   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;
   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: "+this.name);
      System.out.println("Age: "+this.age);
      System.out.println("Branch: "+this.branch);
      System.out.println("Student ID: "+this.Student_id);
   }
   public static void main(String[] args) {
      //Creating an object of the Student class
      Student student = new Student("Krishna", 20, "IT", 1256);
      //Converting the object of Student to Person
      Person person = new Person("Krishna", 20);
      //Converting the object of student to person
      person = (Student) student;
      person.displayPerson();
   }
}

输出

Data of the Person class:
Name: Krishna
Age: 20

简而言之,超类引用变量可以保存子类对象。但是,使用此引用,您只能访问超类成员,如果您尝试访问子类成员,则会生成编译时错误。

public static void main(String[] args) {
   Person person = new Student("Krishna", 20, "IT", 1256);
   person.displayStudent();
}

输出

Student.java:33: error: cannot find symbol
   person.dispalyStudent();
          ^
   symbol: method dispalyStudent()
   location: variable person of type Person
1 error

更新于: 2019-07-30

3K+ 浏览量

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.