A
A
Arthur Braver2016-02-11 09:35:35
Java
Arthur Braver, 2016-02-11 09:35:35

Explain code from Java?

e69b0ec0aa6b4f948f2a8b1739a71d84.PNG
I didn’t understand the explanation of the site, explain why there is an error in line 3, why is the default constructor needed?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Kornachev, 2016-02-11
@Zurus

If no constructor is declared in class A, then by default it contains a constructor without parameters - A(), however, if at least one constructor with parameters is declared, then the constructor A() disappears. But it disappears only when it is not explicitly declared.
Examples

//содержит неявно 1 конструктор A()
class A{
}

//тоже содержит  конструктор A() но явно
class A{
    A(){
    }
}

//cодержит СОДЕРЖИТ ТОЛЬКО 1 конструктор, конструктора A() уже нет
class A{
    A(int x){
    }
}

//есть оба конструктора
class A{
    A(int x){
    }

    A(){}
}

In the example, class A contains one constructor with a parameter - A(int x), which means that it does not have an A() constructor, and you must (if necessary) define it yourself.
The inheritance mechanism is as follows:
- we want to create an object B by calling the constructor B(int b)
- the first line of the constructor should be the string super(...) - with or without parameters, this is necessary so that the parent is first constructed, because B is inherited from A
- if the first line is different, then the compiler substitutes the parent's constructor without parameters - super(), in this case, the creation of the object A using the constructor A() will be called.
- but since this constructor is not defined in object A - an error occurs.
You can fix it like this
Either add the A() constructor to object A, or add an explicit call to the parent super(int x) constructor to the object B constructor (in this case, the parent has only 1 constructor - A(int x)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question