-1

Event class: protected List<Event> eventList = new ArrayList<Event>();

I have another class, a popup box which the user adds event information and an event object is created and added to the list. However i use the eventList, java doesn't recognise it even though it is in same package and protected should be able to be accessed in same package.

How do i access?

Billies Wesley
  • 437
  • 1
  • 6
  • 21

1 Answers1

0

If you are trying to access this list without Event class object, It will not be visible in other class because that class does not extend your Event class.

You can access the list either create an object or extend Event class.

ManojP
  • 6,113
  • 2
  • 37
  • 49
  • This is not true: if the class is in the same package as `Event`, there is no need for it to be a subclass to access protected members. – James_D Mar 15 '18 at 13:29
  • As per definition, it should work but I tried it in eclipse and did not work. – ManojP Mar 15 '18 at 18:04
  • You did something wrong. I tried it in eclipse and it worked fine. – James_D Mar 15 '18 at 18:04
  • Can u plz share the code snippet – ManojP Mar 15 '18 at 18:17
  • public class A { protected int number; } public class B{ //error private int number2 = number; private int number2; public void setNumber2() { //error number2= number; number2= new A().number; } } – ManojP Mar 15 '18 at 18:23
  • @James_D I tried this code which does not work. – ManojP Mar 15 '18 at 18:23
  • Of course `number2 = number` won't work. `B` does not have a field called `number`. The second line is the correct way to do that, and demonstrates that you can access a protected field from another class in the same package. (Change `protected` to `private` to see the difference.) – James_D Mar 15 '18 at 18:39
  • so that's what I said initially, anyways thanks for clarifying the doubt. – ManojP Mar 15 '18 at 19:29
  • But I think the OP is asking about accessibility... presumably they understand you need an object of the correct class to reference an instance variable? – James_D Mar 15 '18 at 19:30