Answer the question
In order to leave comments, you need to log in
Is an initializer required for a child class?
Is an initializer required when creating a child class?
For example, there is an Animal class (takes a name and age), and the Dog class extends it, but takes the same parameters.
In python it would look like this:
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
class Dog(Animal):
def voice(self):
print("GAV")
d = Dog('Sharik', 4)
d.voice()
package Alive;
public class Animal{
String name;
int age;
public Animal(){
this.name = name;
this.age = age;
}
public void voice() {
System.out.println("I'm talking");
}
public void hello() {
System.out.println("Hello");
}
}
package Alive;
public class Cat extends Animal{
public Cat(String name, int age) {
}
public void voice() {
System.out.println("MEW");
}
}
public Cat(String name, int age) {
}
?
Answer the question
In order to leave comments, you need to log in
Firstly, your constructor in Animal does not make sense in the form in which you gave it - without arguments, you just reassigned the class fields to themselves, you probably forgot to write the name and age constructor arguments.
Secondly, Alexander Varakosov is wrong and constructors are not inherited.
Java has default constructors - a constructor without arguments. It is generated automatically by the compiler if no constructor is declared for the class.
In the constructors of child classes, the compiler itself inserts a call to the default parent constructor as the first line, if there is one in the parent class. That. if the child class needs to simply call the parent's default constructor in the constructor, then no constructor can be explicitly declared in the child class. But if the parent does not have a constructor without arguments, then it is necessary to declare a constructor in the child class, at least to call the parent constructor in it.
PS and read more about access modifiers. In java, it is customary to make fields private + getter/setter as needed. In general, take some textbook on java, everything is written there
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question