How to use values of local variables in inherited functions of java?

1.6k views Asked by At

I have 2 classes A and B such that

public class A {
    public String a = "hey";

    public void printA() {
        System.out.println(a);
    }

and

public class B extends A{
    public String a = "Jude";
}

What do I need to do so that the output of the lines below is Jude

B object = new B();
object.printA();    //This should output Jude
4

There are 4 answers

0
Tagir Valeev On

You cannot access the subclass field from the superclass. However you can change it in subclass like this:

public class B extends A {
    B() {
        this.a = "Jude";
    }
}

This way you don't declare the new field, but change the value of existing one. Note that extends A is necessary to specify that B is subclass of A.

Alternatively you may consider using a method instead of field:

public class A {
    public String getA() {
        return "hey";
    }

    public void printA() {
        System.out.println(getA());
    }
}

public class B extends A {
    @Override
    public String getA() {
        return "Jude";
    }
}

Note that in Java "variable" term usually applied to local variables declared within methods. You are speaking about "field", not "variable".

2
CleoR On

Just change your declaration of a to this.a like so.

public class B extends A{
    B(){
        super();
        //Could hardcode this.a to "Jude" here if you want.
    }

    B(String word){
        super();
        this.a = word;
    }
}

a is already defined for B from the superclass A so you need to use "this" to access it.

You can use it like so

B object = new B("Jude");
object.printA(); //"Jude"
0
Bohemian On

Fields can not be overridden. Methods can; use methods instead:

public class A {
    public String getA() {
        return "hey";
    }
    public void printA() {
        System.out.println(getA());
    }
}

public class B extends A {
    public String getA() {
        return "Jude";
    }
}

That's all. If getA() is not called outside these classes, cincdider making it protected.

1
serg.nechaev On

The Java® Language Specification, Java SE 8 Edition

If the class declares a field with a certain name, then the declaration of that field is said to hide any and all accessible declarations of fields with the same name in superclasses, and superinterfaces of the class.

Not sure If I need to further explain it for the audience, but YOU CANNOT "use values of local variables in inherited functions of java", why? See above.