Java Objects and Classes
As an object-oriented programming language, Java supports the following basic concepts:
1. Class:
- The blueprint that defines objects, including attributes and methods.
- Example:
public class Car { ... }
2. Object:
- An instance of a class, having state and behavior.
- Example:
Car myCar = new Car();
3. Inheritance:
- A class can inherit the attributes and methods of another class.
- Example:
public class Dog extends Animal { ... }
4. Encapsulation:
- Privatize the object's state (fields) and access them through public methods.
- Example:
private String name; public String getName() { return name; }
5. Polymorphism:
- Objects can take multiple forms, mainly achieved through method overloading and method overriding.
- Example:
- Method overloading:
public int add(int a, int b) { ... }andpublic double add(double a, double b) { ... } - Method overriding:
@Override public void makeSound() { System.out.println("Meow"); }
6. Abstraction:
- Use abstract classes and interfaces to define methods that must be implemented, without providing concrete implementations.
- Example:
- Abstract class:
public abstract class Shape { abstract void draw(); } - Interfaces:
public interface Animal { void eat(); }
7. Interface:
- Defines methods that a class must implement and supports multiple inheritance.
- Example:
public interface Drivable { void drive(); }
8. Method:
- Defines the behavior of a class; a function contained in a class.
- Example:
public void displayInfo() { System.out.println("Info"); }
9. Method Overloading:
-
A class can have multiple methods with the same name but different parameters.
-
Example:
public class MathUtils { public int add(int a, int b) { return a + b; }public double add(double a, double b) { return a + b; } }
In this section, we focus on the concepts of objects and classes.
- object: An object is an instance of a class (Objects are not about finding a girlfriend), having state and behavior. For example, a dog is an object; its state includes: color, name, breed; its behaviors include: wagging tail, barking, eating, etc.
- class: A class is a template that describes the behavior and state of a class of objects.
In the figure belowBoy, GirlisClass, and each specific person is anobject:

In the figure belowCarisClass, and each specific car is aCarThe class'sobject, and the object contains the car's color, brand, name, etc.

Objects in Java
Now let us understand what an object is. Looking at the real world around us, we find many objects—cars, dogs, people, and so on. All these objects have their own state and behavior.
Take a dog as an example; its state includes: name, breed, color, and its behaviors include: barking, wagging its tail, and running.
Comparing real-world objects and software objects, they are very similar.
Software objects also have state and behavior. A software object's state is its attributes, and its behavior is reflected through methods.
In software development, methods operate on changes to an object's internal state, and objects call each other through methods.
Classes in Java
A class can be viewed as a template for creating Java objects.

Create a simple class from the figure above to understand class definition in Java:
public
class
Dog
{
String
breed
;
int
size
;
String
colour
;
int
age
;
void
eat
(
)
{
}
void
run
(
)
{
}
void
sleep
(
)
{
}
void
name
(
)
{
}
}
A class can contain the following types of variables:
- local variables: Variables defined within a method, constructor, or statement block are called local variables. Variable declaration and initialization are done within the method, and the variable is automatically destroyed after the method ends.
- Member Variable: Member variables are variables defined within the class but outside method bodies. These variables are instantiated when the object is created. Member variables can be accessed by methods, constructors, and certain statement blocks of the class.
- Class variable: Class variables are also declared within the class but outside method bodies, but must be declared as static.
A class can have multiple methods; in the example above, eat(), run(), sleep(), and name() are all methods of the Dog class.
Constructor
Every class has a constructor. If no constructor is explicitly defined for the class, the Java compiler will provide a default constructor for that class.
When creating an object, at least one constructor must be called. A constructor must have the same name as the class, and a class can have multiple constructors.
The following is a constructor example:
public
class
Puppy
{
public
Puppy
(
)
{
}
public
Puppy
(
String
name
)
{
//
This constructor has only one parameter: name
}
}
Creating objects
Objects are created based on classes. In Java, the keyword new is used to create a new object. Creating an object requires the following three steps:
- Declaration: Declare an object, including the object name and object type.
- Instantiation: Use the keyword new to create an object.
- Initialization: When using new to create an object, the constructor is called to initialize the object.
The following is an example of creating an object:
public
class
Puppy
{
public
Puppy
(
String
name
)
{
//
This constructor has only one parameter: name
System
.
out
.
println
(
"
The puppy's name is:
"
name
)
;
}
public
static
void
main
(
String
[
]
args
)
{
//
The following statement will create a Puppy object
Puppy
myPuppy
=
new
Puppy
(
"
tommy
"
)
;
}
}
Compiling and running the program above will print the following result:
小狗的名字是 : tommy
Accessing instance variables and methods
Access member variables and member methods through the created object, as shown below:
/*
Instantiate the object
*/
Object
referenceVariable
=
new
Constructor
(
)
;
/*
Access variables in the class
*/
referenceVariable
.
variableName
;
/*
Access methods in the class
*/
referenceVariable
.
methodName
(
)
;
Declaring a variable with the Object type allows accessing only Object's methods and properties at compile time, but at runtime you can cast it to a specific type to access that type's methods and properties.
Example
The following example shows how to access instance variables and call member methods:
Puppy.java file code:
public
class
Puppy
{
private
int
age
;
private
String
name
;
//
Constructor
public
Puppy
(
String
name
)
{
this
.
name
=
name
;
System
.
out
.
println
(
"
The puppy's name is:
"
name
)
;
}
//
Set the value of age
public
void
setAge
(
int
age
)
{
this
.
age
=
age
;
}
//
Get the value of age
public
int
getAge
(
)
{
return
age
;
}
//
Get the value of name
public
String
getName
(
)
{
return
name
;
}
//
Main method
public
static
void
main
(
String
[
]
args
)
{
//
Creating objects
Puppy
myPuppy
=
new
Puppy
(
"
Tommy
"
)
;
//
Set age through a method
myPuppy
.
setAge
(
2
)
;
//
Call another method to get age
int
age
=
myPuppy
.
getAge
(
)
;
System
.
out
.
println
(
"
The puppy's age is:
"
age
)
;
//
You can also access member variables directly (via getter methods)
System
.
out
.
println
(
"
Variable value:
"
myPuppy
.
getAge
(
)
)
;
}
}
Compiling and running the program above produces the following result:
小狗的名字是 : tommy
小狗的年龄为 : 2
变量值 : 2
Source file declaration rules
In the final part of this section, we will learn the source file declaration rules. When multiple classes are defined in a single source file along with import and package statements, special attention must be paid to these rules.
- A source file can have only one public class
- A source file can have multiple non-public classes
- The name of the source file should match the name of the public class. For example, if the public class in the source file is Employee, the source file should be named Employee.java.
- If a class is defined in a package, the package statement should be on the first line of the source file.
- If the source file contains import statements, they should be placed between the package statement and the class definition. If there is no package statement, the import statements should be at the very beginning of the source file.
- The import and package statements apply to all classes defined in the source file. In the same source file, different classes cannot have different package declarations.
Classes have several access levels, and classes are also divided into different types: abstract classes, final classes, etc. These will be introduced in the access control section.
In addition to the types mentioned above, Java also has some special classes, such as:Inner class, Anonymous class.
Java packages
Packages are mainly used to categorize classes and interfaces. When developing Java programs, you may write hundreds or thousands of classes, so it is necessary to categorize classes and interfaces.
import statement
In Java, if you give a fully qualified name, including the package name and class name, the Java compiler can easily locate the source code or class. The import statement provides a reasonable path so the compiler can find a class.
For example, the following command line tells the compiler to load all classes under the java_installation/java/io path
import java.io.*;
A simple example
In this example, we create two classes:Employee and EmployeeTest.
First open the code editor, paste the code below into it, and save the file as Employee.java.
The Employee class has four member variables: name, age, designation, and salary. The class explicitly declares a constructor that has only one parameter.
Employee.java File Code:
import
java
.
io
.*;
public
class
Employee
{
private
String
name
;
private
int
age
;
private
String
designation
;
private
double
salary
;
//
Constructor of the Employee class
public
Employee
(
String
name
)
{
this
.
name
=
name
;
}
//
Set the value of age
public
void
setAge
(
int
age
)
{
this
.
age
=
age
;
}
//
Get the value of age
public
int
getAge
(
)
{
return
age
;
}
//
Set the value of designation
public
void
setDesignation
(
String
designation
)
{
this
.
designation
=
designation
;
}
//
Get the value of designation
public
String
getDesignation
(
)
{
return
designation
;
}
//
Set the value of salary
public
void
setSalary
(
double
salary
)
{
this
.
salary
=
salary
;
}
//
Get the value of salary
public
double
getSalary
(
)
{
return
salary
;
}
//
Print information
public
void
printEmployee
(
)
{
System
.
out
.
println
(
this
)
;
}
//
Override the toString method
@
Override
public
String
toString
(
)
{
return
"
Name:
"
name
"
\n
"
"
Age:
"
age
"
\n
"
"
Position:
"
designation
"
\n
"
"
Salary:
"
salary
;
}
}
Java programs start execution from the main method. To run this program, it must contain a main method and create an instance object.
The following gives the EmployeeTest class, which instantiates 2 instances of the Employee class and calls methods to set the variable values.
Save the following code in the EmployeeTest.java file.
EmployeeTest.java file code:
import
java
.
io
.*;
public
class
EmployeeTest
{
public
static
void
main
(
String
[
]
args
)
{
//
Create two objects using the constructor
Employee
empOne
=
new
Employee
(
"
RUNOOB1
"
)
;
Employee
empTwo
=
new
Employee
(
"
RUNOOB2
"
)
;
//
Call the member methods of these two objects
empOne
.
setAge
(
26
)
;
empOne
.
setDesignation
(
"
Senior programmer
"
)
;
empOne
.
setSalary
(
1000
)
;
empOne
.
printEmployee
(
)
;
empTwo
.
setAge
(
21
)
;
empTwo
.
setDesignation
(
"
Rookie programmer
"
)
;
empTwo
.
setSalary
(
500
)
;
empTwo
.
printEmployee
(
)
;
}
}
Compile these two files and run the EmployeeTest class; you will see the following result:
$ javac EmployeeTest.java Employee.java
$ java EmployeeTest
名字:RUNOOB1
年龄:26
职位:高级程序员
薪水:1000.0
名字:RUNOOB2
年龄:21
职位:菜鸟程序员
薪水:500.0