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. This new class will be called TimeStamp3 (subclassing Date2 and having a Time3 instance).
I don't entirely understand the part:
include a Time3 instance as a private member
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.
After creating the Time3 class, create another class called TimeStamp3 (silly names...)
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. 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. As you should know, when an instance variable is private
, it is only accessible to members inside the class. This will not make the Time3
class private, just the specific instance of that object inside the Date2
class.
Even when the instance member is private, any methods inside the Date2
class will be able to access that member variable. It's the classes outside of Date2
that won't be able to access that instance. Other classes could potentially access Time3
, just not the the instance of Time3
inside Date2
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.