Java objects and classes

Posted by CowGuy on Mon, 17 Jan 2022 19:29:12 +0100

Classes in Java

  classes can be regarded as templates for creating Java objects. 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 the following types of variables:

  • Local variables: variables defined in methods, construction methods, or statement blocks are called local variables. Variable declaration and initialization are in the method. After the method ends, the variable will be destroyed automatically.
  • 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 variable: class variable is also declared in the class, outside the method body, but must be declared as static type. Static loads as the class loads and takes precedence over the object.

  a variable modified by static is called a static variable, which is essentially a global variable. If a content is shared by all objects, the content should be statically decorated; What is not statically modified is actually a special description of an object. The instance variables of different objects will be allocated different memory spaces. If the member variables in the class have class variables, the class variables of all objects will be allocated to the same memory. Changing the class variable of one object will affect the class variables of other objects, that is, objects share class variables.
  differences between member variables and class variables:

  • The life cycles of the two variables are different: member variables exist with the creation of the object and are released with the recycling of the object; Static variables exist with the loading of the class and disappear with the disappearance of the class.
  • Different calling methods: member variables can only be called by objects; Static variables can be called by objects and class names.
  • Different aliases: member variables are also called instance variables; Static variables are also called class variables.
  • Data storage locations are different: member variables are stored in objects in heap memory, so they are also called object specific data; Static variable data is stored in the static area of the method area (shared data area), so it is also called object shared data.

  pay attention to the following points:

  • Some data are object specific data and cannot be statically modified. Because in that case, the unique data will become the shared data of the object, so there is a problem in the description of things. Therefore, when defining static, you must make it clear whether the data is shared by objects.
  • Static methods can only access static members, not non static members. Because static methods take precedence over the existence of objects when loaded, there is no way to access members in objects.
  • This and super keywords cannot be used in static methods. Because this represents an object, and the class may not have an object when loading, this cannot be used.

Construction method

   each class has a constructor. If the constructor is not explicitly defined for the class, the Java compiler will provide a default constructor for the class. When creating an object, at least one constructor must be called. The name of the constructor 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 */
    }
}

create object

  objects are created from classes. In Java, the keyword new is used 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 will be called to initialize the object.

The following is an example of creating an object:

public class Puppy {
    public Puppy(String name) {
        System.out.println("The dog's name is:" + name);
    }

    public static void main(String[] args) {
        /* The following statement will create a supply object */
        Puppy myPuppy = new Puppy("tommy");
    }
}

Execution results:

The dog's name is: tommy

Accessing instance variables and methods

  access member variables and member methods through created objects:

ObjectReference = new Constructor(); /* Instantiate object */
ObjectReference.variableName; /* Accessing variables in a class */
ObjectReference.MethodName(); /* Accessing methods in classes */

Examples are as follows:

public class Puppy {
    int puppyAge;

    public Puppy(String 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) {
        Puppy myPuppy = new Puppy("tommy"); /* create object */
        myPuppy.setAge(2); /* Set age by method */
        myPuppy.getAge(); /* Call another method to get the age */
        /* You can also access member variables like this */
        System.out.println("Variable value:" + myPuppy.puppyAge);
    }
}

Execution results:

The dog's name is: tommy
 The dog's age is: 2
 Variable value: 2

Source file declaration rules

   when multiple classes are defined in a source file, and there are import statements and package statements, pay special attention to the following rules:

  • There can only be one public class in a source file, and there can be 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 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 the import statement is not in the source file, it should be in the first place.
  • 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, such as abstract classes and final classes. In addition to the types mentioned above, Java also has some special classes, such as internal classes and anonymous classes.

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.

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 will command the compiler to load Java_ All classes in the installation / Java / Io path:

import java.io.*;

  in this example, we create two classes: employee and EmployeeTest. First open the text editor, paste the following code, and save the file as employee java. The Employee class has four member variables: name, age, design, and salary. This class explicitly declares a construction method with only one parameter:

public class Employee {
    String name;
    int age;
    String designation;
    double salary;

    public Employee(String name) { /* Employee Class constructor */
        this.name = name;
    }

    public void empAge(int empAge) { /* Set the value of age */
        age = empAge;
    }

    public void empDesignation(String empDesig) { /* Set the value of design */
        designation = empDesig;
    }

    public void empSalary(double empSalary) { /* Set the value of salary */
        salary = empSalary;
    }

    public void printEmployee() { /* Print information */
        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:

public class EmployeeTest {
    public static void main(String[] args) {
        /* Use the constructor to create two objects */
        Employee empOne = new Employee("RUNOOB1");
        Employee empTwo = new Employee("RUNOOB2");

        /* Call the member methods of these two objects */
        empOne.empAge(26);
        empOne.empDesignation("Senior programmer");
        empOne.empSalary(1000);
        empOne.printEmployee();

        empTwo.empAge(21);
        empTwo.empDesignation("Rookie programmer");
        empTwo.empSalary(500);
        empTwo.printEmployee();
    }
}

Execution results:

name: RUNOOB1
 Age: 26
 Position: Senior Programmer
 Salary: 1000.0
 name: RUNOOB2
 Age: 21
 Position: rookie programmer
 Salary: 500.0

   Java enforces the unification of class name (unique public class) and file name, so there is no need to explicitly declare when referring to other classes. When compiling, the compiler will look for files with the same name according to the class name. Each compilation unit (file) has only one public class, because each compilation unit can only have one public interface represented by the public class. If there is more than one public class, the compiler will report an error. Of course, there can be no public class in a compilation unit.

Topics: Java