Classes and objects (instances)
A class is used as the template for creating objects. When an object is created, all fields and methods declared in the class are copied into an object. The combination of field values in an object is called object state. The methods provide object behavior. An object is also called an instance of a class.
Each object is created by using the operator new
and a constructor that looks like a special kind of method. The primary duty of a constructor is to set an initial object state.
Let's us now have a closer look at Java classes and objects.
Java classes
Java classes are stored in .java
files. Each .java
file may contain several classes. They are compiled by the Java compiler javac
and stored in .class
files. Each .class
file contains one compiled class only.
Each .java
file contains only one public
class. The keyword public
in front of the class name makes it accessible from the classes in other files. The filename must match the public class name. The file...