Answer the question
In order to leave comments, you need to log in
Why is it throwing a java error in the hierarchy example?
Hello. I am engaged in the book of Eldar Khabibullin "Java 7". I reached the hierarchy and there is such an example (on the screen). Why does it give an error and how to fix it? Thank you very much in advance!
Answer the question
In order to leave comments, you need to log in
The thing is that you write tuzik.age = 3; not in the method, but in the class declaration. You can't do that. As you have already been advised, format the code, it will become clearer. Now you have done the following:
* declared class Pet
* declared class Dog inside it
* inside Dog declared two variables of type Dog - tuzik and sharik
* continued to work with these variables in the body of the class. There's a mistake here, you can't do that.
* further declared inside the Pet class Master.
In general, you made a logical error from the second point. Dog should be made a separate file. And Master too. Variables tuzik and sharik should not be inside Dog, you need to write them separately somewhere.
More or less like this:
//Pet.java
public class Pet{
...
}
//Dog.java
public class Dog extends Pet{
...
}
//Master.java
public class Master{
...
}
//Main.java
public class Main{
public static void main(String[] args){
Dog tuzik = new Dog();
...
}
}
Because you need to write the opposite:
Advice - do not forget about tabs, already at the initial level try to write beautiful code, then it will be easier for you and it will be more convenient for you to work with the code than with what I see on your screen
1. Any operations directly in the class body, except for the declaration of fields, must be placed in a block of curly braces.
Dog tuzic = new Dog();
{
tuzic.age = 1;
}
class Dog extends Pet {
Dog tuzic = new Dog();
}
.....
Dog tuzic = new Dog(); // и понеслась:)
Remember first the reference to the object, then its variable.
There is a dog (object) named Tuzik (reference to the object), she is three years old (class variable).
tuzik.age = 3
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question