编译时类型与运行时类型解析

本文详细探讨了Java编程中编译时类型与运行时类型的概念及它们之间的关系。编译时类型由变量声明时的类型决定,而运行时类型取决于实际赋值的对象。在运行过程中,引用变量将执行其运行时类型的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 背景

Java中的许多对象(一般都是具有父子类关系的父类对象)在运行时都会出现两种类型,一种是编译时类型,另一种是运行时类型。

2. 编译时类型

编译时类型由声明该变量时使用的类型决定,比如下方代码块中的main函数类声明的person和male引用变量,其实他们的编译类型分别是Person和Male。编译时引用变量只能调用其编译时类型所具有的方法,因此person是只能调用printAge()方法,而不能调用printStudentInfo()方法

3. 运行时类型

运行时类型由实际赋给该变量的对象决定,同样是person和male引用变量,他们的运行是类型都是Student,所以会看到 male.printAge()和person.printAge()方法运行时都是执行Student内部的printAge()方法。引用变量在运行时则执行它运行时类型所具有的方法

4. 两者关系

public class Male extends Person{
    int age = 30;
    public void printAge() {
        System.out.println(this.getClass().getName() + "'s age is " + age);
    }
}

public class Student extends Male {
    int age = 20;
    public void printAge() {
        System.out.println(this.getClass().getName() + "'s age is " + age);
    }
    public void printStudentInfo() {
        System.out.println("student info");
    }
}

public class Person {
    int age = 1;
    public void printAge() {
        System.out.println(this.getClass().getName() + "'s age is " + age);
    }
    
    public static void main(String[] args) {
        Student student = new Student();
        Male male = student;
        Person person = student;

        student.printAge();
        male.printAge();
        person.printAge();

        System.out.println(student.age);
        System.out.println(male.age);
        System.out.println(person.age);
    }
}

运行结果如下:
运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值