Java基类引用变量

编程入门 行业动态 更新时间:2024-10-22 07:52:38
本文介绍了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基类引用变量

本文发布于:2023-10-31 07:35:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545450.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!