0

This is the scenario:

Package 1 has Public class Machine which has a protected variable protected int speed=3;

I have another package , Package 2 ,which has Public class Car which is a child of Machine class and we also have a Public class Apple which has the main method.

My question is : why speed is accesible from within Car class method/constructor but not from the instance of Car class created from main method present in Appple class.

I am new in java please help ...

Raj_Ame09
  • 1
  • 4

2 Answers2

0

The protected members of the class are only accessible to derived classes of this class, irrespective of where the class is initiated from.

You can think of public/protected/private members as not only providing required encapsulation, but sort of also dictate the levels of hierarchy to which they would be accessible.

public-members can we accessed by all

protected-members can be accessed by itself and its children

private-members can be accessed only by itself

Serial Lazer
  • 1,574
  • 1
  • 4
  • 14
0

To answer your questions,

why speed is accesible from within Car class method/constructor?

This is because the speed is marked as protected, and by definition, a protected member is available to the class and its subclass bodies but not from outside of it. Since Car is subclass of Machine, speed is accessible from within car.

but not from the instance of Car class created from main method present in Appple class?

Here, you are trying to access the speed as public variable from outside of class/subclass body, hence is not accessible.

Please check section 6.6.2 of the JLS for more information.

Santosh
  • 16,973
  • 4
  • 50
  • 75
  • Thanks but we can access protected variable from an instance like..................... ClassB Obj=new ClassB(); Obj.k=3; ///Here,I am accessing the int k as public variable from outside of class/subclass body. – Raj_Ame09 Nov 03 '20 at 13:33
  • Here all classes are in same package....and int k is a protected variable of parent class of ClassB. – Raj_Ame09 Nov 03 '20 at 13:49
  • You cannot do that. Only way to access 'k' from outside of the class is to have public setter method for it. – Santosh Nov 03 '20 at 15:41