Re: (Probably) easy question about inheritance
Zerex71 wrote:
Group,
I'm wondering about the following: Say I have a class called Matrix
which is essentially an array of three numbers, and I call the data
member:
private double array[3];
Typically a matrix uses a two-dimensional array, so it would be private
double[][]. Even more important, a matrix would have different types
(complex, double, BigDecimal, float, integer, etc.) so it should be
generified.
to be used for general math matrix operations. However, I am going to
create a Vector class which subclasses from Matrix, since a vector is
a matrix. In it, I would like to access three data members:
Even though this quote relates to C++, it's still worth saying:
"Welcome to the wonderful world of public inheritance, where the
instincts you've developed in other fields of study -- including
mathematics -- may not serve you as well as you expect." (Point of
order: in C++, public inheritance is the same thing as inheritance in Java)
Think carefully before you have a Vector subclass Matrix -- is there
anything that a generic matrix can do that a vector can't do? AFAIK, the
answer is no (well, a transpose of a column vector is a row vector so
one could make the case that v.transpose().equals(v) should be true, but
in general usage that is probably not going to be expected), but be
careful before you make assumptions.
private double x;
private double y;
private double z;
Are these in the Matrix class or Vector class?
1. Is there a way to refer to x, y, and z when using Vector instead of
array[0..2]? In other words, when I say Vector.x, it automatically
reads/writes array[0]. Is this possible?
Use set/get encapsulation. But no, x, y, and z cannot be aliased to
members of the array.
2. Is there a way that I can avoid duplicating data members between
instances of both classes?
Use protected fields instead of private.
3. Or in inheritance, will I just wind up with six doubles, and have
to deal with it?
Gracious use of protected helps.
Thanks,
Mike
--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth