0

I have 2 classes

class A {
   private int count;
}

class B extends A {
   //need to access count here
}

What standard ways can I use to access it?

user2509983
  • 101
  • 4
  • getters/setters is the words you're looking for. Or make it `protected`. – Maroun Jun 21 '13 at 18:28
  • If `A` and `B` are in the same package, then package private - it is default so there is no keyword - would be mildly preferable to `protected` – emory Jun 21 '13 at 18:35
  • If the attribute is `private`, there's probably for a reason for it. Why should you need to access it? – Joni Jun 21 '13 at 18:36

4 Answers4

7

Either make count protected or add a getCount() method in A.

Maroun
  • 94,125
  • 30
  • 188
  • 241
Imre Kerr
  • 2,388
  • 14
  • 34
  • I think there will be some issues with shadowing (if subclass has same variable name) with protected, isn't it? – kosa Jun 21 '13 at 18:30
  • @Nambari That's certainly something to consider. I'd probably just use a getter. – Imre Kerr Jun 21 '13 at 18:32
  • To expand on this, since the person programming `B` is trying to access `count`, he probably wouldn't make another variable with that name. But saying things like "Nobody would ever..." is a cardinal sin in programming. So yeah, getter it is. – Imre Kerr Jun 21 '13 at 18:41
1

you can declare your field as protected, then it will be accessible to all subclasses and package local classes.

you can also have getters/setters (general practice) if this field can be visible to everyone. Then you just call getCount() method to get count.

please refer here getters/setters example

Community
  • 1
  • 1
Tala
  • 8,888
  • 5
  • 34
  • 38
0
class A {
   private int count;

   public int getCount(){
       return count;
   }
}

class B extends A {
   //need to access count here
}
stinepike
  • 54,068
  • 14
  • 92
  • 112
-1

Java prevents inheriting the private fields in to the sub-class. If you want to access the fields either you could use assessors i.e. getter methods or you could change the field access type to protected or public. Again, protected would only work if the sub-class file is in the same directory. If you have the files in separate directory you would need to change the field access type to Public

Raunak Agarwal
  • 7,117
  • 6
  • 38
  • 62
  • By directory, I think you mean package, in which case, your description of `protected` is not accurate, but instead describes `package-private` – femtoRgon Jun 21 '13 at 18:42