N
N
NikitkOS2016-03-30 13:01:18
Java
NikitkOS, 2016-03-30 13:01:18

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!
06465f5654804913a496069fd8aa1524.png5ea89b19240e4eadb72bfdbe45ea3a7f.pnge5a642c5d393484c8bdc3705d246b231.png

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
Denis Zagaevsky, 2016-03-30
@NikitkOS

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();
        ...
    }
}

I
IceJOKER, 2016-03-30
@IceJOKER

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

E
Evhen, 2016-03-30
@EugeneP2

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;
  }

2. Error, you will have a recursion and the program will crash with a StackOverflowError
class Dog extends Pet {
  Dog tuzic = new Dog();
}

.....

Dog tuzic = new Dog(); // и понеслась:)

When you first create an object of the Dog class, it will go into recursion

K
Konstantin Malyarov, 2016-03-30
@Konstantin18ko

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 question

Ask a Question

731 491 924 answers to any question