I'm having trouble figuring out how to access a private instance variable of the super class. I'm writing an equals method in the Dog class that compares to see if the name and breeds are the same, but name is a private instance variable inside Pet (that Dog inherits).
Here's my code:
public class Pet {
private String name;
public Pet(){
name = "";
}
public Pet(String name){
this.name = name;
}
public boolean equals(Pet other){
return this.name.equals(other.name);
}
}
and my Dog class:
public class Dog extends Pet {
private String breed;
public Dog(String name, String breed) {
super(name);
this.breed = breed;
}
public Dog(){
breed = "";
}
@Override
public boolean equals(Object obj){
if(obj == null){
return false;
}
if(obj.getClass() != this.getClass()){
return false;
}else{
Pet p = (Pet)obj;
Pet q = (Pet)this;
Dog temp = (Dog)obj;
boolean name = q.equals(p);
boolean bred = breed.equals(temp.breed);
return name && bred;
}
}
}
In my main class:
Dog d1 = new Dog("Harry", "Puggle");
Dog d2 = new Dog("Harry", "Pug");
System.out.println(d1.equals(d2));
For some reason it keeps using my Pet class's equal method.
Thanks
@Pshemo has identified the immediate cause of your problem. Your Pet.equals(Object)
does not override `Dog.equals(String)
because the signatures don't match. And your d1.equals(d2)
call is binding to the most closely matching method signature, which is the one with a Pet
formal parameter rather than an Object
formal parameter.
But once you have corrected that, there is another problem in the Dog.equals(String)
method:
Pet p = (Pet)obj;
Pet q = (Pet)this;
boolean name = q.equals(p);
When you fix the signature of Pet.equals, that is going to result in a recursive call to Dog.equals ... and a StackOverflowError
. (Dog.equals will call Dog.equals, which will call Dog.equals, which ...). Basically, q.equals
is the same method as the one that is currently executing. The type casts aren't doing anything ...
Change it to this:
Pet p = (Pet)obj;
boolean name = super.equals(p);
The super
keyword used this way invokes the overridden version of the equals
method.
I'm having trouble figuring out how to access a private instance variable of the super class.
This is a different issue to what is causing your problem. But the answer is that if you want a child classes method to be able to access a private
variable in a parent class, then you need to either add getter and/or setter methods to the parent class, or change the access of the variable to (typically) protected
.