inheritance simple Q

Posted on 2000-02-02
Medium Priority
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() {
    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?

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

Question by:Embt
  • 2

Accepted Solution

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

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

take a look at this page

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