J.Marsomn
J.Marsomn

Reputation: 45

How to access a field in the superclass from a subclass?

I have the two classes here, Minesweeper is a child of Battleship

public class Battleship 
{
 private Part part[];

 public boolean hit(int row, int column)

{
    Part newpart = new Part(row,column);

    for(int i=0; i<part.length;i++)
    {
        if (part[i].equals(newpart))
        {
            part[i].setDestroyed(true);
            return true;
        }
    }

    return false; 
}   

And for the Minesweeper Class I have

public class Minesweeper extends Battleship 
{
   public Minesweeper()
   {
       super(2);
   }

   @Override
   public boolean hit(int row, int column)
   {
       return true;
   }

}

How Can I access the array part without using a getter or making it public. As it says in the assignment that we can't access the array part from outside that class.

Thanks so much for any help

Upvotes: 2

Views: 66

Answers (1)

GhostCat
GhostCat

Reputation: 140407

You would have to change the access modifier for that field from private to protected for example. public would work as well.

But please keep in mind: doing so should be the exception!

Meaning: good OO design is much more about behavior (aka methods) than about fields! In other words: one should have really good reasons to expose fields to child classes. Typically, you work the other way round, like:

abstract class Base {
  abstract int getFoo();
  final void bar() {
    foo = getFoo(); 
  ...

and then classes extending Base simply @Override that method getFoo().

This approach allows you to fix certain behavior on the Base class; while preventing subclasses from changing that behavior; but allowing them to provide those details that are "sub class" specific in the end.

Upvotes: 2

Related Questions