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.

Shunan
  • 3,165
  • 6
  • 28
  • 48
  • variables are not overriden, so this is not possible because it´s not part of the inheritance. variables are just shadowed. – SomeJavaGuy May 30 '16 at 06: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. – Shunan May 30 '16 at 06: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. – SomeJavaGuy May 30 '16 at 06:44

2 Answers2

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.

Hooch
  • 487
  • 3
  • 11
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
Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
  • Thanks @Jim it totally worked for me – Shunan May 30 '16 at 06:57
  • Why we are using a private a? It is also working with protected and public. Just Curious. – Shunan May 30 '16 at 07:17
  • 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. – Jim Garrison May 30 '16 at 07:19