2015-04-03 139 views
1

嗨,这可能看起来像一个非常愚蠢的问题,但我最近进入了Java和我自己的构造函数。构造函数混淆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; 
     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); 
    } 
} 
在我的主要方法的System.out.println

因此,印刷在构造后,我想通过引用我newcreature构造函数的名称,打印名称为“扎克”,但它只是打印名称“迪克”来自我所做的最后一个构造函数。我如何区分这些在同一个类中的构造函数?如果这是一个愚蠢的问题,再次抱歉。

+2

为什么你所有的字段都是'静态'?删除。 – 2015-04-03 09:25:33

+0

工作感谢!哇,我觉得很愚蠢 – 2015-04-03 09:29:10

回答

0

因为你的名字字段是静态的,所以它共享一个共同的内存。所以如果你试图用不同的对象来重新访问它,它会给出相同的输出。

由于您上次更改了值new creatures("Dick", 4, "witch");Dick它将更改为它。

因此消除静电关键字,以得到所需的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 
0

类的所有数据成员都是静态的,这就是为什么每个实例共享相同的成员。当你创建生物的新实例时,构造函数只是用新值覆盖旧值。

在您的代码:

private static String name; 
private static int age; 
private static String type; 

是其中的生物,creature1,creature2共享。

删除静态关键词。

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

}

0

你的领域nameagetype是静态的。这意味着它们被你的所有生物共享。所以你不能说“这个生物的名字是......”,因为一个生物在你的代码中没有名字。正如它写的,你只能说“生物类有这个名字......”,在Java中写成creatures.name=...

所以,你需要从你的字段中删除那个static修饰符。

2

问题在于变量的static关键字。

阅读:enter link description here

静态变量将得到内存只有一次,如果任何对象改变静态变量的值,它会保留其价值。