There are 2 classes of DogTestDrive and Dog. The class Dog is in the folder pets

import pets.Dog; public class DogTestDrive{ public static void main(String[] args) throws Exception { Dog d = new Dog(); System.out.println(d.name); } } 

and

 public class Dog { public String name = "Шарик"; System.out.println(name); } 

I compile through the command line - swears on System.out.println in the class Dog. enter image description here

do not understand why? If you comment out this line of output in the Dog class, everything works.

    1 answer 1

    Because the call to System.out.println(name); inside the class Dog should not occur outside of any method.

    You can do this, for example:

     public class Dog { public String name = "Шарик"; public Dog() { System.out.println(name); } } 

    Thus, the call will be made from the constructor when creating the object.

    • Thank! It worked. And you can read a link about this. I want to understand in more detail why this is the case - Sibkedr
    • What is there to read. System.out is just an object of the PrintStream class. And work with objects of one class, inside another class, is performed only in methods. It can be a static block, a constructor, or a function. Study further, later you will get to know everything in more detail. - Andrew Grow