1

I am a beginner in java. Here is my code

class Super{
public int a;
}
class sub extends Super{
int a = 10;
}

public class test{
public static void main(String args[]){

Super var = new sub();
System.out.println(var.a);//Here I want to print 10 , value of sub class
} 
}

Is it possible and if it is then please tell me how? And I having some problem with the title of this question, so please suggest me an appropriate one as i had explained everything what i want in my code.

3
  • variables are not overriden, so this is not possible because it´s not part of the inheritance. variables are just shadowed. Commented May 30, 2016 at 6:41
  • 1
    Is there any way to achieve this task, one of my friend told me that it can be possible with some getter setter method but we dont know how to do it. Commented May 30, 2016 at 6:44
  • @shubhamnandanwar you could create a method getA in sub and return super.a. But in the end this is senseless in terms of realistic programming, because shadowing a variable is quite a bad programming practice and should be avoided. sub does already know the variable a and shouldn´t declare it again. Commented May 30, 2016 at 6:44

2 Answers 2

1

You should add a getter method for a in your super class

public int getA(){
return a;
}

Subclass will inherit the getter too and you can access the value of a in the sublass. It is also recomebded to make class attribute protected or private instead of public.

Sign up to request clarification or add additional context in comments.

2 Comments

How will this help? Without an override in the subclass getA() will always return 0, which is what the OP doesn't want.
Thanks @Hooch but can you please write the whole program.
0

Make the variables private and add a getA() method in both classes, with the one in the subclass overriding the superclass.

public class Foo
{
    static class Super{
        private int a;
        public int getA() { return a; }
    }

    static class Sub extends Super{
        private int a = 10;
        @Override
        public int getA() { return a; }
    }

    public static void main(String args[]) {
        Super sup1 = new Super();
        Super sup2 = new Sub();
        Sub   sub  = new Sub();
        System.out.println(sup1.getA());
        System.out.println(sup2.getA());
        System.out.println(sub.getA());
    } 
}

This outputs

0
10
10

3 Comments

Thanks @Jim it totally worked for me
Why we are using a private a? It is also working with protected and public. Just Curious.
It is generally good practice to make members private and provide getters/setters. One objective of OO coding is "encapsulation", which means exposing to the outside world only what is required by the interface contract.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.