?
Solved

inheritance simple Q

Posted on 2000-02-02
2
Medium Priority
?
159 Views
Last Modified: 2011-09-20
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
0
Comment
Question by:Embt
  • 2
2 Comments
 
LVL 5

Accepted Solution

by:
mbormann earned 120 total points
ID: 2484695
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

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses

601 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question