Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Objects and Classes

Java Objects and Classes

As an object-oriented programming language, Java supports the following basic concepts:

1. Class:

2. Object:

3. Inheritance:

4. Encapsulation:

5. Polymorphism:

- Method overloading: `public int add(int a, int b) { ... }` and `public double add(double a, double b) { ... }` - Method overriding: `@Override public void makeSound() { System.out.println("Meow"); }`

6. Abstraction:

- Abstract class: `public abstract class Shape { abstract void draw(); }` - Interface: `public interface Animal { void eat(); }`

7. Interface:

8. Method:

9. Method Overloading:

In this section, we focus on the concepts of objects and classes.

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:

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:

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.

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