简体   繁体   English

类实例作为 Java 中的私有成员

[英]Class instance as a private member in Java

I have an assignment where I need to use inheritance and polymorphism:我有一个需要使用继承和多态的作业:

For this assignment, we will subclass the author's Time2 class as Time3 and subclass your previous Date2 to include a Time3 instance as a private member.对于此作业,我们将作者的 Time2 类子类化为 Time3,并将您之前的 Date2 子类化以包含一个 Time3 实例作为私有成员。 This new class will be called TimeStamp3 (subclassing Date2 and having a Time3 instance).这个新类将被称为 TimeStamp3(继承 Date2 并有一个 Time3 实例)。

I don't entirely understand the part:我不完全理解这部分:

include a Time3 instance as a private member包含一个 Time3 实例作为私有成员

Although I do understand that Time3 extends Time2 and TimeStamp3 extends Date2 , I just can't figure out what I need to do to allow Date2 to have access to Time3.尽管我确实理解Time3 extends Time2Time3 extends Time2并且TimeStamp3 extends Date2 ,但我无法弄清楚我需要做什么才能允许 Date2 访问 Time3。

After creating the Time3 class, create another class called TimeStamp3 (silly names...)创建 Time3 类后,再创建一个名为 TimeStamp3 的类(傻名字...)

public class TimeStamp3 extends Date2 {

    private Time3 time;

    //methods, other instance variables etc.

}

A class member is also known as an instance variable.类成员也称为实例变量。 Therefore, your Time3 instance in your Date2 , would be private or protected, rather than public.因此,你的Time3在您的实例Date2 ,将私人或受保护,而不是公众。 It might look like:它可能看起来像:

class TimeStamp3 extends Date2{
...
   private Time3 timeThree; 
...

}

You don't have to worry about accessing the Time3 instance inside Date2 because it is subclassed.您不必担心访问Time3内部实例Date2 ,因为它的子类。 As you should know, when an instance variable is private , it is only accessible to members inside the class.您应该知道,当一个实例变量是private ,它只能被类内的成员访问。 This will not make the Time3 class private, just the specific instance of that object inside the Date2 class.这不会将Time3Time3私有,只会使Time3类中该对象的特定实例成为Date2

Even when the instance member is private, any methods inside the Date2 class will be able to access that member variable.即使实例成员是私有的, Date2类中的任何方法都可以访问该成员变量。 It's the classes outside of Date2 that won't be able to access that instance. Date2之外的类将无法访问该实例。 Other classes could potentially access Time3 , just not the the instance of Time3 inside Date2 .其他类可能会访问Time3 ,而不是Time3中的Date2实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM