recast a superclass attribute

V

VisionSet

class MySuper {

Date date;
}

class MySub extends MySuper {

MyDate date = (MyDate)super.date;
}

Is this sort of thing okay?
I feel I need to do it, but not seen it done before.

I wanted to make my superclass as general as possible so used the Date type,
but subclasses invariably instantiate date themselves as a subclass of Date,
and then need to use it as such.
 
S

Shripathi Kamath

VisionSet said:
class MySuper {

Date date;
}

class MySub extends MySuper {

MyDate date = (MyDate)super.date;
}

Is this sort of thing okay?


Only if Date is derived from MyDate. i.e., MyDate is the superclass of
Date. date needs to contain a reference to an object of the MyDate class.
I feel I need to do it, but not seen it done before.

I wanted to make my superclass as general as possible so used the Date type,
but subclasses invariably instantiate date themselves as a subclass of Date,
and then need to use it as such.

Why bother having a date in the superclass at all?
 
V

VisionSet

MySuper(Date date) { // I throw in a constructor or two for you.
this.date = date;
}


MySub(MyDate date) {
super(date);
}
Only if Date is derived from MyDate. i.e., MyDate is the superclass of
Date. date needs to contain a reference to an object of the MyDate class.

Surely the wrong way round!
I can legally cast my 'Date date' to MyDate in the subclass, because the
subclass controls the type of this object.

MyDate is a subclass of java.util.Date

Why bother having a date in the superclass at all?

erm, because the superclass has methods that operate on the Date object and
do not care if it is actually a subclass of Date.
 
E

Eki Y. Baskoro

Huh? I don't get your question.

What is MyDate? Is it a derived class from Date?
 
D

Daniel Bonniot

VisionSet said:
class MySuper {

Date date;
}

class MySub extends MySuper {

MyDate date = (MyDate)super.date;
}

Is this sort of thing okay?
I feel I need to do it, but not seen it done before.

It is OK, if you pay attention to the following: both classes have their
own field date. It means that if you modified the field in some way,
they will have different values. Which one you access depends on the
static type at the point you access the field. In particular, a method
defined in MySuper will access the MySuper.date field, even if 'this' is
an instance of MySub.

For this reason, I would advise you only to do this with _final_ fields.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top