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
equalsofDogclass is not used at all? If not, its obvious from your code.