Download the JDK
Search the Tutorials
Hide the TOC
Trail: Learning the Java Language
Lesson: Classes and Objects
Section: More on Classes
Classes and Objects
Classes
Declaring Classes
Declaring Member Variables
Defining Methods
Providing Constructors for Your Classes
Passing Information to a Method or a Constructor
Objects
Creating Objects
Using Objects
More on Classes
Returning a Value from a Method
Using the this Keyword
Controlling Access to Members of a Class
Understanding Instance and Class Members
Initializing Fields
Summary of Creating and Using Classes and Objects
Questions and Exercises
Questions and Exercises
Nested Classes
Inner Class Example
Summary of Nested Classes
Questions and Exercises
Enum Types
Questions and Exercises
Annotations
Questions and Exercises
Home Page > Learning the Java Language > Classes and Objects
Summary of Creating and Using Classes and Objects

> A class declaration names the class and encloses the class body between braces. The class name can be preceded by modifiers. The class body contains fields, methods, and constructors for the class. A class uses fields to contain state information and uses methods to implement behavior. Constructors that initialize a new instance of a class use the name of the class and look like methods without a return type.

> You control access to classes and members in the same way: by using an access modifier such as `public` in their declaration.

> You specify a class variable or a class method by using the `static` keyword in the member's declaration. A member that is not declared as `static` is implicitly an instance member. Class variables are shared by all instances of a class and can be accessed through the class name as well as an instance reference. Instances of a class get their own copy of each instance variable, which must be accessed through an instance reference.

> You create an object from a class by using the `new` operator and a constructor. The new operator returns a reference to the object that was created. You can assign the reference to a variable or use it directly.

> Instance variables and methods that are accessible to code outside of the class that they are declared in can be referred to by using a qualified name. The qualified name of an instance variable looks like this:

> >     objectReference.variableName

> The qualified name of a method looks like this:

> >     objectReference.methodName(argumentList)

> >       or

> >     objectReference.methodName()

> The garbage collector automatically cleans up unused objects. An object is unused if the program holds no more references to it. You can explicitly drop a reference by setting the variable holding the reference to `null`.

Previous page: Initializing Fields
Next page: Questions and Exercises: Classes