这段代码有什么问题? (猫类)

What's wrong with this code? (Cat class)

当我编译时,我得到:error, expected ;在喵喵()之后。这段代码有什么问题

public class Cat
{ 
    public static void main(String[]args){
        String name;
        String colour;
        int age;

        Cat c = new Cat();
        c.nome = "Muffin";

        System.out.println(c.name);

        meow(){
            System.out.println("Meow! Meow!");
        }
    }
}

您似乎将 Cat 的属性定义为 main 方法的局部变量,而不是 class 的成员。

并且您的 meow 方法不应该在 main 方法内部,它应该有一个 return 类型。

 public class Cat
 { 
     String name;
     String colour;
     int age;

     public static void main(String[]args)
     {    
        Cat c = new Cat();
        c.name = "Muffin";

        System.out.println(c.name);
     }

     void meow() 
     {
         System.out.println("Meow! Meow!");
     }
 }

你似乎是"trying"在一个方法中定义一个方法,这在Java

中是非法的

应该更像...

public class Cat
{ 
    public static void main(String[]args){
        String name;
        String colour;
        int age;

        Cat c = new Cat();
        c.nome = "Muffin";

        System.out.println(c.name);
        c.meow();
    }

    public void meow(){
        System.out.println("Meow! Meow!");
    }
}

现在,话虽如此,Cat 的属性在 main 方法中被定义为局部变量,实际上并不是 Cat class 的一部分,应该被定义为 class 的一部分(或作为实例字段)

public class Cat
{ 

    String name;
    String colour;
    int age;

    public static void main(String[]args){

        Cat c = new Cat();
        c.nome = "Muffin";

        System.out.println(c.name);
        c.meow();
    }

    public void meow(){
        System.out.println("Meow! Meow!");
    }
}

好吧,看起来更好了,但还有一个问题,字段nome在Cat中没有定义,可能应该是name

c.name = "Muffin";

接下来您要了解的是保护 classes 字段值并通过方法管理访问,通常称为 encapsulation

这里面有几个错误class。那么让我们仔细看看:

1) 您已经在主函数中定义了 Cat 的属性,但您想要的是将它们作为对象属性。 main 方法的静态上下文是在没有具体对象的情况下使用的(并且对于每个实例化的 class 都是相同的(值和方法)

2)您分配给 c.nome 而不是 c.name

3) meow() 缺少 return 类型(这是必要的,除非构造函数(而 meow 不是))

4) meow() 必须在main方法之外

public class Cat {
    String name;
    String colour;
    int age;

    public static void main(String[]args){
        Cat c = new Cat();
        c.name = "Muffin";
        System.out.println(c.name);
    }

    void meow() {
        System.out.println("Meow! Meow!");
    }
}