B
B
BitNeBolt2019-06-15 11:31:47
Java
BitNeBolt, 2019-06-15 11:31:47

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()

For the Dog class, it is not necessary to write the initializer a second time.
In Java, the same thing looks like this:
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");
    }
}

and a cat instead of a dog
package Alive;

public class Cat extends Animal{
    public Cat(String name, int age) {
    }

    public void voice() {
        System.out.println("MEW");
    }
}

Is there any way to avoid writing
public Cat(String name, int age) {
    }
?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
Frozen Coder, 2019-06-15
@BitNeBolt

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 question

Ask a Question

731 491 924 answers to any question