Java objects and classes


It is the intention of the first teacher to reach the goal

1 concept of objects and classes

Java is an object-oriented programming language, and object is the core of object-oriented programming. The so-called object is the entity in the real world, and the object and entity are one-to-one corresponding, that is to say, every entity in the real world is an object, which is a specific concept. The object has the following characteristics:

  • Objects have properties and behaviors.
  • Object has a changing state.
  • Object is unique.
  • Objects are instances of a category.

Everything is an object, and everything in the real world can be regarded as an object.

Object: an object is an instance of a class (the object is not looking for a girlfriend), and has state and behavior. For example, a dog is an object whose status includes: color, name and breed; Behaviors: wagging tail, barking, eating, etc.
Class: a class is a template that describes the behavior and state of a class of objects.

In the following figure, boy s and girl s are classes, and each person is an object of this class

In the following figure, the car is a class, and each specific car is an object of the car class. The object includes the color, brand, name, etc. of the car.

2 objects in Java

Now let's take a closer look at what objects are. Look at the real world around you, and you will find many objects, cars, dogs, people and so on. All of these objects have their own state and behavior.

Take a dog for example. Its state includes: name, breed, color, and its behavior includes: barking, wagging its tail, and running.

Compared with real objects and software objects, they are very similar.

Software objects also have states and behaviors. The state of a software object is an attribute, and its behavior is reflected through methods.

In software development, methods operate on the change of internal state of objects, and the mutual invocation of objects is also completed through methods

3 classes in Java

Classes can be viewed as templates for creating Java objects.

Create a simple class from the above figure to understand the definition of classes 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 variables of the following types:

  • Local variables: variables defined in a method, constructor, or statement block are called local variables. Variable declaration and initialization are in the method. After the method ends, the variable will be automatically destroyed.
  • Member variables: member variables are variables defined in the class and outside the method body. This variable is instantiated when the object is created. Member variables can be accessed by methods in a class, constructor methods, and statement blocks of a specific class.
  • Class variables: class variables are also declared in the class, outside the method body, but must be declared as static type.

A class can have multiple methods. In the above example, eat(), run(), sleep(), and name() are all methods of the Dog class.

3.1 naming rules for Java class names

  1. Class name should be underlined (_) Or start with a letter, preferably a letter.

  2. The first letter should be capitalized. If the class name consists of multiple words, the first letter of each word should be capitalized.

  3. The class name cannot be a keyword in Java, such as boolean, this, int, etc.

  4. Class names cannot contain any embedded spaces or periods, except underscores (_) And dollar sign ($) characters

3.2 definition of Java classes

To define a class in Java, you need to use the class keyword, a custom class name, and a pair of braces to represent the program body. The complete syntax is as follows:

[public][abstract|final]class<class_name>[extends<class_name>][implements<interface_name>] {
    // Define attribute section
    // Define method section

Note: in the above syntax, the part in the brackets "[]" can be omitted, and the vertical line "|" represents "or relationship", for example, abstract|final, indicating that the abstract or final keywords can be used, but the two keywords cannot appear at the same time.

The description of each keyword is as follows:

  • Public: means "shared". If you use the public modifier, it can be accessed by other classes and programs. The main class of each Java program must be a public class. The class used by other classes and programs as a public tool should be defined as a public class.
  • Abstract: if a class is modified by abstract, it is an abstract class. An abstract class cannot be instantiated, but it can have abstract methods (methods modified with abstract) and concrete methods (methods modified without abstract). All subclasses that inherit from this abstract class must implement all abstract methods in this abstract class (unless the subclass is also an abstract class).
  • Final: if the class is decorated with final, it is not allowed to inherit.
  • Class: key to declare a class.
  • class_name: name of the class.
  • extends: means to inherit from other classes.
  • implements: indicates the implementation of some interfaces.
  • property_type: indicates the type of the member variable.
  • property: indicates the name of the member variable.
  • function(): indicates the name of the member method.

4 construction method

Each class has a constructor. If you do not explicitly define a constructor for a class, the Java compiler will provide a default constructor for that class.

When creating an object, at least one constructor must be called. The constructor name must have the same name as the class. A class can have multiple constructors.

The following is an example of a construction method:

public class Puppy{
    public Puppy(){
    public Puppy(String name){
        // This constructor has only one parameter: name

5 creating objects

Objects are created from classes. In Java, the keyword new is used to create a new object. Creating objects 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 creating an object using new, the constructor will be 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 dog's name is : " + name ); 
   public static void main(String[] args){
      // The following statement will create a purchase object
      Puppy myPuppy = new Puppy( "tommy" );
Compile and run the above program, and the following results will be printed:
The dog's name is tommy

6 accessing instance variables and methods

Access member variables and member methods through the created object, as follows:

/* Instanced object */
Object referenceVariable = new Constructor();
/* Accessing variables in a class */
/* Accessing methods in a class */

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("The dog's name is : " + name ); 
   public void setAge( int age ){
       puppyAge = age;
   public int getAge( ){
       System.out.println("The dog's age is : " + puppyAge ); 
       return puppyAge;
   public static void main(String[] args){
      /* create object */
      Puppy myPuppy = new Puppy( "tommy" );
      /* Set age by method */
      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 ); 
Compile and run the above program to produce the following results:
The dog's name is tommy
 Puppy age: 2
 Variable value: 2

7 source file declaration rules

In the last part of this section, we will learn the declaration rules of the source file. Pay special attention to these rules when defining multiple classes in a source file, as well as 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, if the class name of 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 in 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 at the top of the source file.
  • The import statement and package statement are valid for all classes defined in the source file. You cannot declare different packages for different classes in the same source file.
    Classes have several access levels, and classes are also divided into different types: abstract classes and final classes. These are described in the access control section.

In addition to the types mentioned above, Java also has some special classes, such as internal classes and anonymous classes.

8 Java package

Packages are mainly used to classify classes and interfaces. When developing Java programs, hundreds of classes may be written, so it is necessary to classify classes and interfaces.

8.1 import statement

In Java, if you give a complete qualified name, including 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 class.

For example, the following command line commands the compiler to load Java_ All classes under the installation/java/io path


8.2 a simple example

In this example, we create two classes: Employee and EmployeeTest.

First open the 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, design, and salary. This class explicitly declares a constructor that has only one parameter. file code:

public class Employee{
   String name;
   int age;
   String designation;
   double salary;
   // Constructor of Employee class
   public Employee(String name){ = name;
   // Set the value of age
   public void empAge(int empAge){
      age =  empAge;
   /* Set the value of design*/
   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("position:" + designation );
      System.out.println("salary:" + salary);

Programs are executed from the main method. To run this program, you must include the main method and create an instance object.

The EmployeeTest class is given below. This class instantiates two instances of Employee class and calls methods to set the value of variables.

Save the following code in employeetest Java file. file code:

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.empDesignation("Senior programmer");
      empTwo.empDesignation("Rookie programmer");
Compile these two files and run the EmployeeTest class. You can see the following results:
$ javac
$ java EmployeeTest 
 Age: 26
 Position: Senior Programmer
 Salary: 1000.0
 Name: RUNOOB2
 Age: 21
 Position: rookie programmer
 Salary: 500.0
Code words are not easy to find a triple connection

Tags: Java

Posted by jamesxg1 on Fri, 03 Jun 2022 22:27:12 +0530