class Animal {
// Animal class members
private String ageOfDog;
}
// Child Class
class Dog extends Animal {
// Dog inherits traits from Animal
private Integer ageOfDog;
}
in the above example, in the parent class, im having a field with type of string. and in the child class im having the same field with different type.
I know i ll get a type error. may i know why is it.
pls anyone help me with this.
Could you perhaps explain what you wanted to happen here? Why would you create a member variable in the subclass with the same name, but a different type? Did you perhaps want access to the member variable from the parent class? If so, just mark that variable as protected instead of private.
PS: it is extremely odd for a variable called ageOfDog to be a String instead of a numeric type.
I was just considering an example. ignore the dog example…but consider an same field in parent and child class with different types for some task need.
why do we get the type error, is it because of the getter and setter methods are public. if it is private, the methods can’t be used right…
then how do i resolve this or why the type error is actually happening here?
can u pls describe to me
Fundamentally the reason is because an instance of the subclass will still have the private member variables of the superclass even though the subclass cannot access them. If you reuse the same variable name even with the same type you have done something called shadowing the superclass variable and this can lead to incredible confusion. Just use distinct member variable names in your subclass.
You might as well ask why you cannot have two member variables of the same name with different types like this:
public class SomeClass {
private int someVariable;
private String someVariable;
// ...
}
Suffice it to say it is invalid and the compiler cannot create valid Bytecode with the code you are trying to write. Beyond that it is difficult to say what you should do unless you have a specific case in mind.
Oh so in case like this,
public class SomeClass {
protected String someVariable;
// …
}
//childclass
public class ChildClass extends SomeClass {
private int someVariable;
// …
}
if we declare it as protected, we will be able to use it?
Yes, declaring the variable as protected gives us access to it. Still pretty sure trying to shadow the variable with the same name and a different type is invalid though.
Okkk, now
i have a enum declared in the child class
public class SomeClass {
private String someVariable;
// …
}
public class ChildClass extends SomeClass {
public enum AtTypeEnum {
TYPEA(“TypeA”),
TYPEB(TypeB);