For example, if in the class 'animal' there was the String variable 'species,' and I made a subclass 'Cat,' how could I initialize the species variable so that for cat, it contained the value "cat"? Sorry for the dumb question.
Asked
Active
Viewed 44 times
-1
-
1[java initialize base class fields in subclass constructor](https://stackoverflow.com/questions/51845169/java-initialize-base-class-fields-in-subclass-constructor) Or just enter the following in the search box at the top of this Web page: ___[java] initialize superclass member in subclass___ – Abra Oct 16 '22 at 04:42
-
1Does this answer your question? [java initialize base class fields in subclass constructor](https://stackoverflow.com/questions/51845169/java-initialize-base-class-fields-in-subclass-constructor) – tgdavies Oct 16 '22 at 05:30
-
Don't use `static` for your fields. Static is class-level, not instance-level. Use the constructor to pass values. In any case, you should provide a [mre] with the code you have now. – Mark Rotteveel Oct 16 '22 at 05:30
-
Please provide enough code so others can better understand or reproduce the problem. – Community Oct 16 '22 at 12:24
1 Answers
0
This is an example that shows that you can have a superclass that has a general field (in our case species) and that field can be instantiated in the subclasses of the superclass with different values. The subclass can have a default constructor that sets a default value for the general field (in our case the species has the default value of cat) and we can have constructors that help us set a new spice for the subclass Cat.
public class Test {
public static void main(String[] args) {
Animal animal = new Animal();
Cat cat = new Cat();
Cat tiger = new Cat("tiger");
Cat jaguar = new Cat("jaguar");
System.out.println("Animal specie: " + animal.species);
System.out.println("Normal cat specie: " + cat.species);
System.out.println("Tiger cat specie: " + tiger.species);
System.out.println("Jaguar cat specie: " + jaguar.species);
}
}
class Animal {
String species;
public Animal() {
species = "animal";
}
}
class Cat extends Animal {
public Cat() {
species = "cat";
}
public Cat(String specie) {
species = specie;
}
}

Uran Lajci
- 61
- 4