Java 学习 类和对象
课程目的:
With the knowledge you now have of the basics of the Java programming language, you can learn to write your own classes. In this lesson, you will find information about defining your own classes, including declaring member variables, methods, and constructors.
You will learn to use your classes to create objects, and how to use the objects you create.
This lesson also covers nesting classes within other classes, and enumerations。
1、构建自己的类,包括变量申明、方法以及构造器;
构造器在创建对象时自动调用。
2、学会创建对象,并且使用对象;
3、涉及到Nesting class 和 enumerations.
命名细节
1、定义类时,首字母要大些;
2、类中的方法名第一个单词为动词。
方法定义细节
1、method 由返回值、方法名、参数、实现主体组成。
对象
A typical Java program creates many objects, which as you know, interact by invoking methods. Through these object interactions, a program can carry out various tasks, such as implementing a GUI, running an animation, or sending and receiving information over a network. Once an object has completed the work for which it was created, its resources are recycled for use by other objects.
典型的程序创建很多对象,通过调用对象中的方法进行程序交互来完成各项任务,如GUI,消息接收等。
2、constructor
All classes have at least one constructor.可以有多个构造器。
As before, the compiler determines which constructor to call, based on the number and the type of arguments.
当有多个构造器时,编译器通过参数的类型和数量确定使用哪个构造器。
3、access levels
Modifier | Class | Package | Subclass | World |
---|---|---|---|---|
public |
Y | Y | Y | Y |
protected |
Y | Y | Y | N |
no modifier | Y | Y | N | N |
private |
Y | N | N | N |
The first data column indicates whether the class itself has access to the member defined by the access level. As you can see, a class always has access to its own members. The second column indicates whether classes in the same package as the class (regardless of their parentage) have access to the member. The third column indicates whether subclasses of the class declared outside this package have access to the member. The fourth column indicates whether all classes have access to the member.
匿名类
Anonymous classes are often used in graphical user interface (GUI) applications.
疑问:
Class Members :class variable 和 class method主要用于什么情况?