构造函数混淆Java
您好,这似乎是一个非常愚蠢的问题,但我最近进入了java并自学了构造函数构造函数混淆Java,java,constructor,Java,Constructor,您好,这似乎是一个非常愚蠢的问题,但我最近进入了java并自学了构造函数 public class creatures { private static String name; private static int age; private static String type; public creatures( String name, int age, String type) { this.name = name; th
public class creatures {
private static String name;
private static int age;
private static String type;
public creatures( String name, int age, String type) {
this.name = name;
this.age = age;
this.type = type;
System.out.println("The creature's name is " + name + " \nThe creatures age is" + age + " \nThe creatures type is " + type);
}
public static void main(String [] args) {
creatures newcreature = new creatures("Zack", 100, "alien");
creatures newcreature1 = new creatures("Jonny", 500, "vampire");
creatures newcreature2 = new creatures("Dick", 4, "witch");
System.out.println(newcreature.name);
}
}
因此,在我的main方法中的system.out.println中,在打印构造函数之后,我想通过引用我的新生物构造函数的名称来打印名称“Zack”,但它只打印我创建的上一个构造函数的名称“Dick”。如何区分同一类中的这些构造函数?再次抱歉,如果这是一个愚蠢的问题 因为您的名称字段是静态的,所以它共享一个公共内存。因此,如果您尝试使用不同的对象重新引用它来访问它,它将提供相同的输出 自从你上次更改了新生物(“迪克”,4,“女巫”)代码>与
Dick
一起更改为它
因此,删除static关键字以获得所需的o/p
public class creatures {
private String name;
private int age;
private String type;
public creatures( String name, int age, String type) {
this.name = name;
this.age = age;
this.type = type;
System.out.println("The creature's name is " + name + " \nThe creatures age is" + age + " \nThe creatures type is " + type);
}
public static void main(String [] args) {
creatures newcreature = new creatures("Zack", 100, "alien");
creatures newcreature1 = new creatures("Jonny", 500, "vampire");
creatures newcreature2 = new creatures("Dick", 4, "witch");
System.out.println(newcreature.name);
}
}
输出
Zack
类的所有数据成员都是静态的,这就是为什么每个实例共享同一个成员。当您创建新的生物实例时,构造函数只是用新值覆盖旧值 在代码中:
private static String name;
private static int age;
private static String type;
在生物、创造者1、创造者2之间共享
删除静态关键字
public class creatures {
private String name;
private int age;
private String type;
public creatures(String name, int age, String type) {
this.name = name;
this.age = age;
this.type = type;
System.out.println("The creature's name is " + name
+ " \nThe creatures age is" + age + " \nThe creatures type is "
+ type);
}
public static void main(String[] args) {
creatures newcreature = new creatures("Zack", 100, "alien");
creatures newcreature1 = new creatures("Jonny", 500, "vampire");
creatures newcreature2 = new creatures("Dick", 4, "witch");
System.out.println(newcreature.name);
}
}您的字段
名称
、年龄
和类型
是静态的。这意味着它们被你所有的生物共享。所以你不能说“这个生物的名字是……”,因为你的密码里没有这个生物的名字。正如所写的那样,您只能说“这个生物类有这个名字…”,而在Java中,这个名字是写在bioses.name=…
中的
因此,您需要从字段中删除
static
修饰符。问题在于变量处的static关键字
请阅读以下内容:
静态变量将只获得一次内存,如果任何对象更改静态变量的值,它将保留其值。为什么所有字段都是静态的?把它拿开,这很有效,谢谢!哇,我觉得自己太傻了