Java : Using parent class method to access child class variable

60,368

Solution 1

class A {
    private int x = 5;

    protected int getX() {
        return x;
    }

    protected void setX(int x) {
        this.x = x;
    }

    public void print() {
        // getX() is used such that 
        // subclass overriding getX() can be reflected in print();
        System.out.println(getX());
    }
}

class B extends A {
    public B() {
        // setX(10);  // perhaps set the X to 10 in constructor or in main
    }

    public static void main(String[] args) {
        B b = new B();
        b.setX(10);
        b.print();
    }
}

EDITED

Below is a general answer using abstract class and method to solve similar scenario:

abstract class SuperA {
    protected abstract Object getObj();

    public void print() {
        System.out.println(getObj());
    }
}

class A extends SuperA {
    @Override
    protected Object getObj() {
        // Your implementation
        return null; // return what you want
    }
}

class B extends A {
    @Override
    protected Object getObj() {
        // Your implementation
        return null; // return what you want
    }

    public static void main(String[] args) {
        B b = new B();
        b.print();
    }
}

Solution 2

After reading all the answers posted here, I got what I was looking for. The following is what I feel is the best answer for my question :

public class A {
    private int x = 5;    
    protected int getX(){
        return x; 
    }    
    public void print(){
        System.out.println(getX());
    }
}
public class B extends A {
    private int x = 10;
    protected int getX(){
        return x; 
    }  
    public static void main(String[] args) {
        B b = new B();
        b.print();
    }
}

Setting up a protected getter and overriding it is better than overriding the print() method itself, as there could be any other huge method in place of the print method which might need to access the value of the child class variable(s).

Solution 3

To solve your question you have to define the fields in the parent class A like protected (so it will be inherited on the child class) and set the field value x inside the constructor in the child class B. The print method is also inherited from A class so you can invoke it directly from parent class.

I hope this can help you.

public class A 
{
    // fields declaration 
    protected int x = 5;

    public void print()
    {
        System.out.println(x);
    }
}



public class B extends A 
{

    public B()
    {
        // set child x value. The field have been defined in the parent class
        x = 10;
    }

    public static void main(String[] args) 
    {
        A a = new A();
        a.print(); // print 5

        B b = new B();
        b.print(); // print 10
    }

}
Share:
60,368
Jayant
Author by

Jayant

I am a university student majoring in Mathematics and Computing. I have a high interest in learning new programming languages. Over the years, I have developed a good command in a few programming languages like C, C++ and Java. I am highly influenced by the object-oriented programming paradigm and its intricacies. I work mostly in Linux (RHEL). Apart from programming, I have a huge interest in field of Network Security. Moreover, I regularly make web-applications, mostly in LAMP(Linux Apache PHP MySQL).

Updated on July 09, 2022

Comments

  • Jayant
    Jayant almost 2 years

    I have the following scenario :

    public class A {
    
        private int x = 5;
    
        public void print()
        {
            System.out.println(x);
        }
    }
    
    
    public class B extends A {
    
        private int x = 10;
    
        /*public void print()
        {
            System.out.println(x);      
        }*/
    
        public static void main(String[] args) {
            B b = new B();
            b.print();
        }
    
    }
    

    On executing the code, the output is : 5.

    How to access the child class(B's) variable(x) via the parent class method?

    Could this be done without overriding the print() method (i.e. uncommenting it in B)?

    [This is important because on overriding we will have to rewrite the whole code for the print() method again]

    EDITED

    More Clarification :-

    • The motive of the question is to use the value of a child class private variable from its parent class method. This doesn't require changing the value of the parent class private variable in order to achieve the desired result.
    • The answers posted here, though, led me to my desired answer, which I have posted below.

    (Thanks all for your time and help )

  • Admin
    Admin almost 12 years
    That works too, though what if x has to be changed at one point? This is restricted to the example given.
  • Victor Wong
    Victor Wong almost 12 years
    Make a setter of X also then.
  • Admin
    Admin almost 12 years
    @VictorWong This isn't a real getter, the variable isn't actually there.
  • Admin
    Admin almost 12 years
    Nice all-around solution. This is pretty OOP =D. Also, very much C#-like.
  • Victor Wong
    Victor Wong almost 12 years
    @Shingetsu, Thanks, but I know nothing about C#, I plan to learn it but my job doesn't allow...
  • Admin
    Admin almost 12 years
    basically, C# is just an elegant version of Java. If you know Java well already you won't have much trouble learning it, though knowing .NET and C++ would come in handy =D.
  • Jayant
    Jayant almost 12 years
    This is a great answer (solves the problem). It would be nice to declare private variable and return it in the getX() method instead of just returning the values directly. If you allow, i could edit your answer to do the above (and accept it).
  • Jayant
    Jayant almost 12 years
    This would work well. But it actually beats the motive of the question. What is required is to use the value of the variable from the child class in a parent class function.
  • Victor Wong
    Victor Wong almost 12 years
    Then you can just override getX() method and return the required value.
  • Jayant
    Jayant almost 12 years
    Yes, this is what Sawas's answer does (adding the edits indicated by my comment below).
  • Victor Wong
    Victor Wong almost 12 years
    I don't know what you intend to do as you said you don't want to override the print method, so I was thinking overriding the getX() method was not preferable too, anyway just provide you and others the two approaches that solves similar problems. This is a common practice to abstract the method such that subclass can be aware of what is needed to implement such that parent method can be accessing the correct content.
  • Mohammad Taha
    Mohammad Taha almost 12 years
    i update the answer to provide a setter which the sublass uses on its constructor. This should have the same effect.
  • Jayant
    Jayant about 10 years
    @kakacii Yes, though VictorWong's answer does not answer the question precisely, people find it more useful. I have changed my choice. Thanks :)
  • frank17
    frank17 over 8 years
    what if I need to have main function in the parent class A?
  • Victor Wong
    Victor Wong over 8 years
    @Jayant I can't see any difference between my general solution (not the first one, but edited one) and your answer here, except you replace obj with x. No offense, but I want to know why my solution is not precise enough.
  • Keith Tyler
    Keith Tyler almost 7 years
    Having to re-implement the exact same method in the child class completely defeats the purpose of having the parent class at all. The goal (at least IMHO) is to minimize code repetition by implementing the method only once, in the parent class. Isn't that the point of inheritance?
  • Victor Wong
    Victor Wong almost 7 years
    @KeithTyler you are right, but also take note that the solution just shows one method in class A and B specific to the question. In reality, there could be many methods and what you may need is to override one or two of them in child class but reuse other methods from parent class.