The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
Consider the following class:
public class IdentifyMyParts { public static int x = 7; public int y = 3; }
Question: What are the class variables?
Answer: x
Question: What are the instance variables?
Answer: y
Question: What is the output from the following code:
IdentifyMyParts a = new IdentifyMyParts(); IdentifyMyParts b = new IdentifyMyParts(); a.y = 5; b.y = 6; a.x = 1; b.x = 2; System.out.println("a.y = " + a.y); System.out.println("b.y = " + b.y); System.out.println("a.x = " + a.x); System.out.println("b.x = " + b.x); System.out.println("IdentifyMyParts.x = " + IdentifyMyParts.x);
Answer: Here is the output:
a.y = 5 b.y = 6 a.x = 2 b.x = 2 IdentifyMyParts.x = 2
Because x
is defined as a public static int
in the class IdentifyMyParts
, every reference to x
will have the value that was last assigned because x
is a static variable (and therefore a class variable) shared across all instances of the class. That is, there is only one x
: when the value of x
changes in any instance it affects the value of x
for all instances of IdentifyMyParts
.
This is covered in the Class Variables section of Understanding Instance and Class Members.
Exercise: Write a class whose instances represent a single playing card from a deck of cards. Playing cards have two distinguishing properties: rank and suit. Be sure to keep your solution as you will be asked to rewrite it in Enum Types.
Answer:
Card.java
.
Exercise: Write a class whose instances represents a full deck of cards. You should also keep this solution.
Answer: See Deck.java
.
Exercise: Write a small program to test your deck and card classes. The program can be as simple as creating a deck of cards and displaying its cards.
Answer: See DisplayDeck.java
.