inheritance simple Q

public class SuperClass {

  public int x;
  int y= 8;
  public void m1( int a ) {
  }

  SuperClass( ) {
  }
}

class SubClass extends SuperClass {

    private float f;
    void m2() {
      return;
    }
    SubClass() {
    }
}

class T {

  public static void main( String [] args) {
    int i;
    float g = 3;
    SubClass b = new SubClass( );
    i = b.y;  //why b.y is legal here?
      
    System.out.println(i);
 
  }
}
 

Can anybody explain why the b.y is legal here?

Thanks
EmbtAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

mbormannCommented:
See the thing is that when u subclass any superclass forget temporarily in ur mind that it has a parent ,it is a separate entity by itself.

so since u have not specified it as private but given the variable 'int y' a default package scope it can be accessed by any class in the package,this is dangerous.

Going  back ,visualise it back as superclass-subclass.
Always give some access specifier and by the good design practise that mostly all of ur super class variables be private,it is generally given 'private int y' ,u can also give it protected if u want it to be visible in ur subclass ,i.e
if u keep it 'protected int y' then this wont casue error
b.y

if u keep it 'private int y' then this is casue error
b.y

take a look at this page
http://www.cse.unsw.edu.au/~timm/pub/subjects/oois96/rules.html
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.