Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Java objects and classes


May 10, 2021 Java


Table of contents


Java objects and classes

Java is an object-oriented language. The following basic concepts are supported:

  • Polymorphic
  • Inherited
  • Packaging
  • Abstract
  • Class
  • Object
  • Instance
  • Method
  • Message resolution

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

  • Object: An object is an instance of a class that has states and behaviors. For example, a dog is an object whose status is: color, name, breed, behavior: wagging its tail, barking, eating, etc.
  • Class: A class is a template that describes the behavior and state of a class of objects.

The object in Java

Now let's take a closer look at what an object is. L ook around the real world and you'll see a lot of objects, cars, dogs, people and so on. All of these objects have their own states and behaviors.

Take a dog, for example, whose status is: name, breed, color, behavior: barking, wagging and running.

They are very similar to real-world and software objects.

Software objects also have states and behaviors. The state of the software object is the property, and the behavior is embodied by method.

In software development, the method manipulates the change of the internal state of the object, and the mutual call of the object is also done by means.

The class in Java

Classes can be thought of as templates for creating Java objects.

Understand the definition of a class in Java with a simple class like this:

public class Dog{
   String breed;
   int age;
   String color;
   void barking(){
   }
   
   void hungry(){
   }
   
   void sleeping(){
   }
}

A class can contain the following types of variables:

  • Local variable: A variable defined in a method, construction method, or statement block is called a local variable. Both the variable declaration and initialization are in the method, and when the method is complete, the variable is automatically destroyed.
  • Member variable: A member variable is a variable defined in a class, outside the method body. T his variable is instantiated when the object is created. Member variables can be accessed by methods, construction methods, and statement blocks of a particular class in a class.
  • Class variables: Class variables are also declared in the class, outside the method body, but must be declared as static types.

A class can have multiple methods, in the example above: barking() hungry() sleeping() methods of the Dog class.


The construction method

Each class has a construction method. If you do not explicitly define a construction method for a class, the Java compiler provides a default construction method for the class.

When you create an object, call at least one construction method. The name of the construction method must be the same as the class, and a class can have more than one construction method.

Here's an example of a construction method:

public class Puppy{
   public Puppy(){
   }

   public Puppy(String name){
      // 这个构造器仅有一个参数:name
   }
}

Create an object

Objects are created from classes. I n Java, use the keyword new to create a new object. Creating an object requires the following three steps:

  • Declaration: Declares an object, including the object name and object type.
  • Instantiation: Use new to create an object.
  • Initialization: When you create an object with new the construction method is called to initialize the object.

Here's an example of creating an object:

public class Puppy{
   public Puppy(String name){
      //这个构造器仅有一个参数:name
      System.out.println("Puppy Name is :" + name ); 
   }
   public static void main(String []args){
      // 下面的语句将创建一个Puppy对象
      Puppy myPuppy = new Puppy( "tommy" );
   }
}

Compile and run the program above and print out the following results:

Puppy Name is :tommy

Access instance variables and methods

Access member variables and member methods through objects that have been created, as follows:

/* 实例化对象 */
ObjectReference = new Constructor();
/* 访问其中的变量 */
ObjectReference.variableName;
/* 访问类中的方法 */
ObjectReference.MethodName();

The following example shows how to access instance variables and call member methods:

public class Puppy{
   int puppyAge;
   public Puppy(String name){
      // 这个构造器仅有一个参数: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){
      /* 创建对象 */
      Puppy myPuppy = new Puppy( "tommy" );
      /* 通过方法来设定age */
      myPuppy.setAge( 2 );
      /* 调用另一个方法获取age */
      myPuppy.getAge( );
      /*你也可以像下面这样访问成员变量 */
      System.out.println("Variable Value :" + myPuppy.puppyAge ); 
   }
}

Compile and run the program above, resulting in the following results:

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

The source file claims the rule

At the end of this section, we'll look at the claims rules for the source file. Pay special attention to these rules when defining multiple classes import file, and there are import and package statements.

  • There can only be one public class in a public file
  • A source file can have more than one public class
  • The name of the source file public consistent with the class name of the public class. For example, if the public of the public class in the source file is Employee the source file should Employee.java
  • If a class is defined in a package, the package be on the first line of the source file.
  • If the source file import statement, it should be placed package the package statement and the class definition. If package no package statement, the import statement should be at the top of the source file.
  • import package are valid for all classes defined in the source file. In the same source file, you cannot declare different packages for different classes.

Classes have several access levels, and classes are divided into different types: abstract classes, final final and so on. These will be covered in the Access Control section.

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


Java package

Packages are primarily used to classify classes and interfaces. When developing Java programs, hundreds or thousands of classes can be written, so it is necessary to classify classes and interfaces.

The Import statement

In Java, the Java compiler can easily locate the source code or class if you give a complete qualified name, including the package name and class name. Import statements are used to provide a reasonable path so that the compiler can find a class.

For example, the following command line will command 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 text editor and paste the following code in. Note Save the file as an employee .java.

The Employee class has four member variables: name, age, designation, and salary. The class explicitly declares a construction method that has only one argument.

import java.io.*;
public class Employee{
   String name;
   int age;
   String designation;
   double salary;
   // Employee 类的构造器
   public Employee(String name){
      this.name = name;
   }
   // 设置age的值
   public void empAge(int empAge){
      age =  empAge;
   }
   /* 设置designation的值*/
   public void empDesignation(String empDesig){
      designation = empDesig;
   }
   /* 设置salary的值*/
   public void empSalary(double empSalary){
      salary = empSalary;
   }
   /* 打印信息 */
   public void printEmployee(){
      System.out.println("Name:"+ name );
      System.out.println("Age:" + age );
      System.out.println("Designation:" + designation );
      System.out.println("Salary:" + salary);
   }
}

Programs are main the main method. In order to run the program, you must include the main method and create an instance object.

The EmployeeTest class is given below, which instantiates two instances of the Employee class and calls the method to set the value of the variable.

Save the following code in the EmployeeTest .java file.

import java.io.*;
public class EmployeeTest{

   public static void main(String args[]){
      /* 使用构造器创建两个对象 */
      Employee empOne = new Employee("James Smith");
      Employee empTwo = new Employee("Mary Anne");

      // 调用这两个对象的成员方法
      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();
   }
}

By compiling both files and running the EmployeeTest class, you can see the following results:

C :> javac Employee.java
C :> vi EmployeeTest.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