Java 简明教程

Java - Classes and Objects

Java 是一种面向对象的编程语言。在 Java 中, classes and objects 是面向对象编程系统中的重要基础特性,Java 支持以下基础 OOPs concepts -

Java is an Object-Oriented programming language. In Java, the classes and objects are the basic and important features of object-oriented programming system, Java supports the following fundamental OOPs concepts

  1. Classes

  2. Objects

  3. Inheritance

  4. Polymorphism

  5. Encapsulation

  6. Abstraction

  7. Instance

  8. Method

  9. Message Passing

在本教程中,我们将了解 Java 类和对象,创建类和对象,访问类方法等。

In this tutorial, we will learn about Java Classes and Objects, the creation of the classes and objects, accessing class methods, etc.

What are Java Classes?

class 是用于创建单个对象的蓝图(或者可以称之为一个类的 data type 对象类型)。在 Java 中,所有内容都与类和对象相关。每个类都有可以通过对象访问和操作的 methodsattributes

A class is a blueprint from which individual objects are created (or, we can say a class is a data type of an object type). In Java, everything is related to classes and objects. Each class has its methods and attributes that can be accessed and manipulated through the objects.

例如,如果您希望为学生创建课程。这种情况下,“Student”将是一个课程,而学生记录(例如 student1、student2 等)将成为对象。

For example, if you want to create a class for students. In that case, "Student" will be a class, and student records (like student1, student2, etc) will be objects.

我们还可以认为课程是可以用于生成对象的工厂(用户定义的蓝图)。

We can also consider that class is a factory (user-defined blueprint) to produce objects.

Properties of Java Classes

  1. A class does not take any byte of memory.

  2. A class is just like a real-world entity, but it is not a real-world entity. It’s a blueprint where we specify the functionalities.

  3. A class contains mainly two things: Methods and Data Members.

  4. A class can also be a nested class.

  5. Classes follow all of the rules of OOPs such as inheritance, encapsulation, abstraction, etc.

Types of Class Variables

课程可以包含任何以下变量类型。

A class can contain any of the following variable types.

  1. Local variables − Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.

  2. Instance variables − Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.

  3. Class variables − Class variables are variables declared within a class, outside any method, with the static keyword.

Creating (Declaring) a Java Class

要创建(声明)一个类,需要使用 access modifiers ,后跟类关键字和类名。

To create (declare) a class, you need to use access modifiers followed by class keyword and class_name.

Syntax to create a Java class

用以下语法在 Java 中创建(声明)类:

Use the below syntax to create (declare) class in Java:

access_modifier class class_name{
  data members;
  constructors;
  methods;
  ...;
}

Example of a Java Class

在这个例子中,我们创建了一个课程“Dog”。类属性包括 breed、age 和 color。类方法是 setBreed()、setAge()、setColor() 和 printDetails()。

In this example, we are creating a class "Dog". Where, the class attributes are breed, age, and color. The class methods are setBreed(), setAge(), setColor(), and printDetails().

// Creating a Java class
class Dog {
  // Declaring and initializing the attributes
  String breed;
  int age;
  String color;

  // methods to set breed, age, and color of the dog
  public void setBreed(String breed) {
    this.breed = breed;
  }
  public void setAge(int age) {
    this.age = age;
  }
  public void setColor(String color) {
    this.color = color;
  }

  // method to print all three values
  public void printDetails() {
    System.out.println("Dog detials:");
    System.out.println(this.breed);
    System.out.println(this.age);
    System.out.println(this.color);
  }
}

What are Java Objects?

object 是类型为 class 的变量,是面向对象编程系统的一个基本组件。一个类拥有方法和数据成员(属性),这些方法和数据成员是通过一个 object 访问的。因此,对象是一个类的实例。

An object is a variable of the type class, it is a basic component of an object-oriented programming system. A class has the methods and data members (attributes), these methods and data members are accessed through an object. Thus, an object is an instance of a class.

如果我们考虑真实世界,我们可以发现周围有很多对象,如汽车、狗、人等。所有这些对象都有状态和行为。

If we consider the real world, we can find many objects around us, cars, dogs, humans, etc. All these objects have a state and a behavior.

如果我们考虑一只狗,那么它的状态是名称、品种和颜色,而行为是吠叫、摇尾巴和奔跑。

If we consider a dog, then its state is - name, breed, and color, and the behavior is - barking, wagging the tail, and running.

如果您比较软件对象和真实世界对象,它们拥有非常类似的特征。软件对象也有状态和行为。软件对象的状态存储在字段中,而行为通过方法显示。因此,在软件开发中,方法操作对象内部状态,而对象间的通信是通过方法完成的。

If you compare the software object with a real-world object, they have very similar characteristics. Software objects also have a state and a behavior. A software object’s state is stored in fields and behavior is shown via methods. So, in software development, methods operate on the internal state of an object, and the object-to-object communication is done via methods.

Creating (Declaring) a Java Object

正如之前提到的,一个类为对象提供蓝图。所以基本上,一个对象是从一个类创建的。在 Java 中,使用 new 关键字创建新对象。

As mentioned previously, a class provides the blueprints for objects. So basically, an object is created from a class. In Java, the new keyword is used to create new objects.

从一个类创建对象时有三个步骤 −

There are three steps when creating an object from a class −

  1. Declaration − A variable declaration with a variable name with an object type.

  2. Instantiation − The 'new' keyword is used to create the object.

  3. Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object.

Syntax to Create a Java Object

请考虑以下语法在 Java 中创建课程对象:

Consider the below syntax to create an object of the class in Java:

Class_name object_name = new Class_name([parameters]);

注:参数是可选的,可以在类中使用 constructors 时使用。

Note: parameters are optional and can be used while you’re using constructors in the class.

Example to Create a Java Object

在这个示例中,我们正在创建一个名为 obj 的 Dog 类对象并访问其方法。

In this example, we are creating an object named obj of Dog class and accessing its methods.

// Creating a Java class
class Dog {
  // Declaring and initializing the attributes
  String breed;
  int age;
  String color;

  // methods to set breed, age, and color of the dog
  public void setBreed(String breed) {
    this.breed = breed;
  }
  public void setAge(int age) {
    this.age = age;
  }
  public void setColor(String color) {
    this.color = color;
  }

  // method to print all three values
  public void printDetails() {
    System.out.println("Dog detials:");
    System.out.println(this.breed);
    System.out.println(this.age);
    System.out.println(this.color);
  }
}

public class Main {
  public static void main(String[] args) {
    // Creating an object of the class Dog
    Dog obj = new Dog();

    // setting the attributes
    obj.setBreed("Golden Retriever");
    obj.setAge(2);
    obj.setColor("Golden");

    // Printing values
    obj.printDetails();
  }
}
Dog detials:
Golden Retriever
2
Golden

Accessing Instance Variables and Methods

实例变量和方法可以通过创建对象来访问。要访问实例变量,以下是完全限定路径 −

Instance variables and methods are accessed via created objects. To access an instance variable, following is the fully qualified path −

/* First create an object */
ObjectReference = new Constructor();

/* Now call a variable as follows */
ObjectReference.variableName;

/* Now you can call a class method as follows */
ObjectReference.MethodName();

Example

在这个示例中,我们创建了一个名为 Puppy 的类。在 Puppy 类构造函数中,打印小狗的名字,以便在创建对象时打印其名字。添加了实例变量 puppyAge,并且可以使用 getter/setter 方法来处理年龄。在 main 方法中,使用 new 运算符创建一个对象。使用 setAge() 方法更新年龄,并且使用 getAge(),打印年龄。

In this example, We’ve created a class named Puppy. In Puppy class constructor, puppy name is printed so that when the object is created, its name is printed. An instance variable puppyAge is added and using getter/setter method, we can manipulate the age. In main method, an object is created using new operator. Age is updated using setAge() method and using getAge(), the age is printed.

public class Puppy {
   int puppyAge;

   public Puppy(String name) {
      // This constructor has one parameter, <i>name</i>.
      System.out.println("Name chosen 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) {
      /* Object creation */
      Puppy myPuppy = new Puppy( "tommy" );

      /* Call class method to set puppy's age */
      myPuppy.setAge( 2 );

      /* Call another class method to get puppy's age */
      myPuppy.getAge( );

      /* You can access instance variable as follows as well */
      System.out.println("Variable Value :" + myPuppy.puppyAge );
   }
}

如果我们编译并运行以上程序,它将产生以下结果 −

If we compile and run the above program, then it will produce the following result −

Name chosen is :tommy
Puppy's age is :2
Variable Value :2

Rules for using the Classes and Objects Concepts

现在,让我们了解源文件声明规则(使用 Java 类和对象方法)。在源文件中声明类、导入语句和包语句时,这些规则至关重要。

Let’s now look into the source file declaration rules (to use the Java classes & objects approach). These rules are essential when declaring classes, import statements, and package statements in a source file.

  1. There can be only one public class per source file.

  2. A source file can have multiple non-public classes.

  3. The public class name should be the name of the source file as well which should be appended by .java at the end. For example − the class name is public class Employee{} then the source file should be as Employee.java.

  4. If the class is defined inside a package, then the package statement should be the first statement in the source file.

  5. If import statements are present, then they must be written between the package statement and the class declaration. If there are no package statements, then the import statement should be the first line in the source file.

  6. Import and package statements will imply to all the classes present in the source file. It is not possible to declare different import and/or package statements to different classes in the source file.

类有几个不同的访问级别,还有不同的类型,如抽象类、final 类等。我们将在访问修饰符章节中解释所有这些。

Classes have several access levels and there are different types of classes; abstract classes, final classes, etc. We will be explaining about all these in the access modifiers chapter.

除了上述类型的类之外,Java 还有一些称为内部类和匿名类的特殊类。

Apart from the above mentioned types of classes, Java also has some special classes called Inner classes and Anonymous classes.

More Examples on Java Classes and Objects

Example 1

Employee 类有四个实例变量:name、age、designation 和 salary。该类有一个明确定义的构造函数,它接受一个参数。

The Employee class has four instance variables - name, age, designation and salary. The class has one explicitly defined constructor, which takes a parameter.

import java.io.*;
public class Employee {

   String name;
   int age;
   String designation;
   double salary;

   // This is the constructor of the class Employee
   public Employee(String name) {
      this.name = name;
   }

   // Assign the age of the Employee  to the variable age.
   public void empAge(int empAge) {
      age = empAge;
   }

   /* Assign the designation to the variable designation.*/
   public void empDesignation(String empDesig) {
      designation = empDesig;
   }

   /* Assign the salary to the variable	salary.*/
   public void empSalary(double empSalary) {
      salary = empSalary;
   }

   /* Print the Employee details */
   public void printEmployee() {
      System.out.println("Name:"+ name );
      System.out.println("Age:" + age );
      System.out.println("Designation:" + designation );
      System.out.println("Salary:" + salary);
   }
}

正如本教程中前面提到的,处理从 main 方法开始。因此,为了让我们运行这个 Employee 类,应该有一个 main 方法并且应该创建对象。我们为这些任务创建一个单独的类。

As mentioned previously in this tutorial, processing starts from the main method. Therefore, in order for us to run this Employee class there should be a main method and objects should be created. We will be creating a separate class for these tasks.

Example 2

以下是 EmployeeTest 类,它创建两个 Employee 类实例,并为每个对象调用方法来为每个变量分配值。

Following is the EmployeeTest class, which creates two instances of the class Employee and invokes the methods for each object to assign values for each variable.

将以下代码保存在 EmployeeTest.java 文件中。

Save the following code in 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");

      // Invoking methods for each object created
      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();
   }
}

现在,编译这两个类,然后运行 EmployeeTest 以查看结果,如下所示 −

Now, compile both the classes and then run EmployeeTest to see the result as follows −

C:\> javac Employee.java
C:\> javac EmployeeTest.java
C:\> java EmployeeTest
Name:James Smith
Age:26
Designation:Senior Software Engineer
Salary:1000.0
Name:Mary Anne
Age:21
Designation:Software Engineer
Salary:500.0