-3

For example,

public class Folder {
    // ...
    private List<Subfolder> subfolders;
}

and

public class Subfolder extends Folder {
    // ...
}

If I'm understanding correctly, a Subfolder will inherit all the fields of the Folder superclass, including its List<Subfolder>. However, because the list is private to Folder, and as long as I don't write any accessor or mutator methods for the list, I can rest assured that a Subfolder will not be able to do anything with Folder's list of subfolders. What I feel conflicted about is whether this is considered good design. If a Subfolder is unable to access the Folder's list of subfolders, why inherit it at all?

3 Answers3

1

A child class inherit the non-private fields from its parent. What you have there is a bad design because a parent class should not know about their child classes.

You have a high coupling which is bad because you are making Folder depend on its child.

Frankely Diaz
  • 886
  • 1
  • 9
  • 16
  • Thanks for confirming my suspicion. However, in Herbert Schildt's _Java: A Beginner's Guide_, he says "even though a subclass includes all of the members of its superclass, it cannot access those members of the superclass that have been declared private." So, unless I'm not privy to some technicality, the child does inherit all fields, including private, it just cannot access them. –  Jul 18 '15 at 03:43
1
  • Abstraction

    One possiblity is an abstract Folder, it might delegate behavior that it does not implement to SubFolder instances. I see no requirement that SubFolder must be an instance of Folder vis-a-vis compiling Folder.

  • Encapsulation

    A private field is not inherited because the field is not directly accesible (it is encapsulated). Mutability often requires synchronization amongst threads (or something like Copy-On-Write). Regardless, Wikipedia says encapsulation is used to hide the values or state of a structured data object inside a class, preventing unauthorized parties' direct access to them.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

No as OOP follows a strict hierarchy. From this,

Think of it this way, all dogs are animals, but not all animals are dogs. All dogs bark, but not all animals bark.

You can not have a super class call a subclass method as the super class does not inherit anything from the subclass.

Community
  • 1
  • 1
nonamorando
  • 1,556
  • 2
  • 14
  • 33