Java基类引用变量 [英] Java Base Class Reference Variable

查看:310
本文介绍了Java基类引用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以为基类引用变量分配基类对象或派生类对象的地址。

True / False ?

True/False?

有人能告诉我一个这样的例子吗?我是Java的新手,正在尝试理解Java的语言特定术语。谢谢。

Can anybody show me an example of what this means? I'm new to Java and am trying to understand language specific terms of Java. Thanks.

我想这个例子就是我在下面写的代码:

I think an example of this would be the code I've written below:

public class B extends A {
    A a = new A();
    A ab = new B();
}

class A {

}

我认为既然两个引用变量都是有效的语法(在Eclipse中),那么答案是正确的。

I think that since both reference variables are valid syntax (in Eclipse) then the answer is true.

推荐答案


可以为基类引用变量分配基类对象或派生类对象的地址。

A base class reference variable may be assigned the address of either a base class object or a derived class object.

是/否?

是的,因为所有派生类对象都是基类的实例,但不是相反的。

True, because all derived class object is an instance of the base class, but not the other way round.


有人能给我看一个这意味着什么的例子吗?我是Java的新手,正在尝试理解Java的语言特定术语。谢谢。

Can anybody show me an example of what this means? I'm new to Java and am trying to understand language specific terms of Java. Thanks.

首先,你需要知道什么是基类和派生类。

First of all, you need to know what is a base class and a derived class.

基类也称为父类或超类是由另一个类扩展的类。一个简单的例子是 Animal class

Base class also known as parent class or super class is a class which is extended by another. A simple example would be Animal class.

当一个子类从它的超类扩展时。例如, Lion class

While a child class extends from its super class. For example, Lion class.

我们知道所有的狮子都是动物。但并非所有动物都是狮子。
子类只是超类的子集。

We know that all lions are animals. But not all animals are essentially lions. The subclass is just a subset of the superclass.

因此,当我们有基类引用时,我们可以将派生类对象分配给它。

Hence, when we have a base class reference, we are allowed to assign derived class object into it.

示例:

class Animal{

}

class Lion extends Animal{

}


Animal someAnimal = new Lion(); //because all lions are animals

然而,反过来却是不真实的。因此在Java中不可能也不允许:

However, the reverse is untrue. Thus not possible and not allowed in Java:

Lion lion = new Animal(); //not allowed in Java.

这篇关于Java基类引用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆