The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
July 2000

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

Re: derived classes

Posted by RJK on July 06, 2000 at 4:16 PM

The new derived class *does* inherits the private members, but these members are *not* directly accessible by any new functions in the derived class. It makes sense if you think about it, here's a simple (and overused!) example.

Let's say you have a class called "Person".

NB - I am writing this very late at night after a long session with C++. I will guarantee that my syntax goes badly astray here - I'm aiming for clarity over accuracy!

class Person {
private String name;
private int age;

// plus some public functions, including accessors and modifiers
}

Of course, these public functions can freely work on name and age, even though name and age are private (because they are part of the same class).

Now, we extend "person" to model an "employee" of a company.

class Employee extends person
{
private int employeeId;
private int salary;

public void promote(void)
{
salary *= 2; // salary doubles (!)
}
}


Now, the new class Employee has the following components:

name
age
salary
employeeId

Note that name and age are still there... but...

This is the crucial point : a function which you add to the employee class (like promote() ) CANNOT access, directly, any data which is defined in the parent class as being private (like age). So, therefore, we *couldn't* have:

public void promote (void)
{
age++; // bang. Compile error. This is private to person
salary *= 2;
}

Think about it. Why should functions which deal strictly with employee details, be allowed to fiddle with details which stricly pertain to the person?

If you do need to modify either name or age, then use an accessor function defined in person.

For people who believe that this distinction between parent and derived class is too harse, we have the other alternative -declare name and age as *protected*. This data would then behave as before (ie private to the world outside the class), except it WOULD be accessible to the derived class.

Hope this helps - any further details from easyfix@eidosnet.co.uk.

Regards,
RJK



Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us