【发布时间】: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();。 -
不是您的反对者,但请小心,因为您已经提出了几个被反对的问题,如果这种情况发生太多,网站软件会自动阻止您提出更多问题.如果您还没有这样做,请浏览tour、help center 和how to ask a good question 部分,以了解本网站的工作原理并帮助您改进当前和未来的问题,从而有望避免禁令。
-
现在在下一课中,介绍一个类 Animal 作为 Dog 和 Cat 的扩展。
-
@popovitsj 你的意思是我应该把“动物”放在上面吗?我想它是从上到下读取的,所以我使用的变量必须事先写好。
-
@HovercraftFullOfEels 好的,我会通读的。谢谢你^^