【问题标题】:Did I understand it? [closed]我明白了吗? [关闭]
【发布时间】:2015-03-08 20:29:23
【问题描述】:

我不知道这是否是一种错误的提问方式,因为这实际上是我在另一个 question 中得到的提示的延续。

问题是,我想知道静态关键字是做什么的,我想我理解了。我现在的问题是,我理解正确吗?以及如何创建“Dogs”的实例?

class Dog {
static String form /* of all dogs */ =  "Doggy-like";
static int quantity /* of dogs */ = 5;

String colour; /* of a specific dog */
String size; /* of a specific dog */ 

}

class Cat {
static String form /* of all cats */ = "Catty-like";    
static int quantity/* of cats */ = 3;

String colour; /* of a specific cat */
String size; /* of a specific cat */


}

public class Animals {
public static void main(String[] args){
    System.out.println("There are "+Cat.quantity+" cats.");
    System.out.println("There are "+Dog.quantity+" dogs.");
    /* EDIT: */
    Dog Mike = new Dog();
    Dog Pete = new Dog();
    Cat Sushi = new Cat();
    Cat Michael = new Cat();
    Cat Pete = new Cat();
    Dog.Mike.size="Big";
    Dog.Mike.colour="Red";
    Dog.Pete.size="Small";
    Cat.Sushi.size="Small";

    }
}

我还想知道那些皮特猫和狗之间是否存在冲突,以及这样定义它们的大小是否正确。在公共类 Animals 中或在它们各自的类(或其他类)中创建它是否有区别?

【问题讨论】:

  • 看起来像。您可以通过调用适当的构造函数来创建类的实例,在本例中为Dog dog = new Dog();
  • 不是您的反对者,但请小心,因为您已经提出了几个被反对的问题,如果这种情况发生太多,网站软件会自动阻止您提出更多问题.如果您还没有这样做,请浏览tourhelp centerhow to ask a good question 部分,以了解本网站的工作原理并帮助您改进当前和未来的问题,从而有望避免禁令。
  • 现在在下一课中,介绍一个类 Animal 作为 Dog 和 Cat 的扩展。
  • @popovitsj 你的意思是我应该把“动物”放在上面吗?我想它是从上到下读取的,所以我使用的变量必须事先写好。
  • @HovercraftFullOfEels 好的,我会通读的。谢谢你^^

标签: java static


【解决方案1】:

是的,您已经在类中定义了静态字段,并使用 ClassName.fieldName 在静态上下文中访问它。所以你是对的。

如果你想实例化 Dog,你可以在你的 main 中这样做:

Dog dog = new Dog();

默认情况下,我们得到不接受任何参数的构造函数。

【讨论】:

    【解决方案2】:

    要创建 Dog 的实例,只需这样做

    Dog d = new Dog();
    

    在这种情况下,类的default constructor 被调用。

    【讨论】:

      猜你喜欢
      • 2014-04-02
      • 2015-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-14
      • 1970-01-01
      • 2014-04-18
      相关资源
      最近更新 更多