Before understanding Java classes and objects, let's briefly introduce object-oriented programming. Programming is the design of programs through objects. The object represents an entity and the entity can be clearly identified.
Java as an object-oriented language. The following basic concepts are supported:
Polymorphism
inherit
encapsulation
abstract
kind
object
Example
method
Message parsing
In this section we focus on the concepts of objects and classes.
Object : An object is an instance of a class and has state and behavior. For example, a dog is an object. Its status includes: color, name, and breed; its behaviors include: wagging its tail, barking, eating, etc.
Class : A class is a template that describes the behavior and status of a class of objects.
Now let's take a closer look at what an object is. If you look at the real world around you, you will find that there are many objects around you, such as cars, dogs, people, etc. All these objects have their own state and behavior.
Take a dog as an example. Its status includes: name, breed, and color, and its behaviors include: barking, wagging its tail, and running.
Comparing real objects and software objects, they are very similar.
Software objects also have state and behavior. The state of a software object is its attribute, and its behavior is reflected through methods.
In software development, methods operate on changes in the internal state of objects, and mutual calls between objects are also accomplished through methods.
Classes can be thought of as templates for creating Java objects.
Let’s understand the definition of classes in Java through the following simple class:
public class Dog{
String breed;
int age;
String color;
void barking(){
}
void hungry(){
}
void sleeping(){
}
}
A class can contain variables of the following types:
Local variables : Variables defined in methods, constructors or statement blocks are called local variables. Variable declaration and initialization are all in methods. After the method ends, the variables will be automatically destroyed.
Member variables : Member variables are variables defined in the class and outside the method body. Such variables are instantiated when the object is created. Member variables can be accessed by class methods, constructors, and class-specific statement blocks.
Class variables : Class variables are also declared in the class, outside the method body, but they must be declared as static type.
A class can have multiple methods. In the above example: barking()
, hungry()
and sleeping()
are all methods of the Dog class.
Every class has constructor methods. If no constructor is explicitly defined for a class, the Java compiler will provide a default constructor for the class.
When creating an object, at least one constructor method must be called. The name of the constructor must be the same as the class. A class can have multiple constructors.
Here is an example constructor:
public class Puppy{
publicPuppy(){
}
public Puppy(String name){
// This constructor has only one parameter: name
}
}
Objects are created based on classes. In Java, use the keyword new
to create a new object. Creating an object requires the following three steps:
Declaration : Declare an object, including object name and object type.
Instantiation : Use the keyword new
to create an object.
Initialization : When using new
to create an object, the constructor method is called to initialize the object.
Here is an example of creating an object:
public class Puppy{
public Puppy(String name){
//This constructor has only one parameter: name
System.out.println("Puppy Name is :" + name );
}
public static void main(String []args){
//The following statement will create a Puppy object Puppy myPuppy = new Puppy( "tommy" );
}
}
Compile and run the above program, and the following results will be printed:
Puppy Name is :tommy
Access member variables and member methods through the created object as follows:
/* Instantiate object */
ObjectReference = new Constructor();
/* Access the variables */
ObjectReference.variableName;
/* Access methods in the class */
ObjectReference.MethodName();
The following example shows how to access instance variables and call member methods:
public class Puppy{
int puppyAge;
public Puppy(String name){
// This constructor has only one parameter: name
System.out.println("Passed Name is :" + name );
}
public void setAge( int age ){
puppyAge = age;
}
public int getAge( ){
System.out.println("Puppy's age is :" + puppyAge );
return puppyAge;
}
public static void main(String []args){
/* Create object */
Puppy myPuppy = new Puppy( "tommy" );
/* Set age through methods */
myPuppy.setAge(2);
/* Call another method to get age */
myPuppy.getAge( );
/*You can also access member variables as follows */
System.out.println("Variable Value :" + myPuppy.puppyAge );
}
}
Compiling and running the above program produces the following results:
Passed Name is :tommy
Puppy's age is :2
Variable Value:2
In the final part of this section, we'll learn about the declaration rules for source files. Pay special attention to these rules when defining multiple classes in a source file and when there are import
statements and package
statements.
There can only be one public
class in a source file
A source file can have multiple non- public
classes
The name of the source file should be consistent with the class name of the public
class. For example: the class name of the public
class in the source file is Employee
, then 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 an import
statement, it should be placed between the package
statement and the class definition. If there is no package
statement, the import
statement should be first in the source file.
The import
statement and package
statement are valid for all classes defined in the source file. In the same source file, different package declarations cannot be given to different classes.
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 chapter.
In addition to the types mentioned above, Java also has some special classes, such as inner classes and anonymous classes.
Packages are mainly used to classify classes and interfaces. When developing Java programs, you may write hundreds or thousands of classes, so it is necessary to classify classes and interfaces.
In Java, if a complete qualified name is given, including the package name and class name, the Java compiler can easily locate the source code or class. The Import
statement is used to provide a reasonable path so that the compiler can find a certain class.
For example, the following command line will instruct the compiler to load all classes in the java_installation/java/io path
import java.io.*;
In this example, we create two classes: Employee and EmployeeTest.
First open a text editor and paste the following code into it. Note that the file is saved as Employee.java.
The Employee class has four member variables: name, age, designation and salary. The class explicitly declares a constructor method with only one parameter.
import java.io.*;
public class Employee{
String name;
int age;
String designation;
double salary;
// Constructor of Employee class public Employee(String name){
this.name = name;
}
//Set the value of age public void empAge(int empAge){
age = empAge;
}
/*Set the value of designation*/
public void empDesignation(String empDesig){
designation = empDesig;
}
/*Set the value of salary*/
public void empSalary(double empSalary){
salary = empSalary;
}
/* Print information */
public void printEmployee(){
System.out.println("Name:"+ name );
System.out.println("Age:" + age );
System.out.println("Designation:" + designation );
System.out.println("Salary:" + salary);
}
}
Program execution starts from the main
method. In order to run this program, the main
method must be included and an instance object must be created.
The EmployeeTest class is given below, which instantiates two instances of the Employee class and calls methods to set the values of variables.
Save the following code in the EmployeeTest.java file.
import java.io.*;
public class EmployeeTest{
public static void main(String args[]){
/* Create two objects using constructor */
Employee empOne = new Employee("James Smith");
Employee empTwo = new Employee("Mary Anne");
//Call the member methods of these two objects empOne.empAge(26);
empOne.empDesignation("Senior Software Engineer");
empOne.empSalary(1000);
empOne.printEmployee();
empTwo.empAge(21);
empTwo.empDesignation("Software Engineer");
empTwo.empSalary(500);
empTwo.printEmployee();
}
}
Compile these two files and run the EmployeeTest class. You can see the following results:
C:>javacEmployee.java
C :> vi EmployeeTest.java
C:>javacEmployeeTest.java
C :>javaEmployeeTest
Name:James Smith
Age:26
Designation:Senior Software Engineer
Salary:1000.0
Name:Mary Anne
Age:21
Designation:Software Engineer
Salary:500.0