Basic concepts of classes and objects

object-oriented programming

Java is an object-oriented programming. The main concepts of object-oriented programming are abstraction, encapsulation, inheritance and polymorphism.

  • Abstract: To ignore those aspects of the problem that are not relevant to the current goal in order to pay more attention to those aspects related to the current goal;
  • Encapsulation: An information concealment technology that uses abstract data types to encapsulate data and data-based operations together.
  • Inheritance: A new class can acquire the properties and behavior of an existing class (called a base class or a parent class), and a new class is a derived class (or subclass) of an existing class.
  • Polymorphism: Refers to the coexistence of different methods with the same name in a program.

Declarations and references to classes

Each class has its own attributes and methods; for example, time is sometimes, minutes, seconds, which are attributes; reading time is the method.
Let's create a time class that includes hours, minutes, and seconds. Read time is the method.

public class Clock {
    //Member variables
    int hour;
    int minute;
    int second;
    //Member Method
    public void setTime(int newH,int newM,int newS){
        hour=newH;
        minute=newM;
        second=newS;
    }
    public void showTime(){
        System.out.println(hour+":"+minute+":"+second);
    }
    public static void main(String args[]){
    	//create object
        Clock clocks=new Clock();
        //Call Method Set Time
        clocks.setTime(1,20,40);
        //Call method print time
        clocks.showTime();
    }
}

Data Members

File Circle.java;
Class variables, such as the circumference, need to be declared static for constant values commonly used in the system.

public class Circle {
    static double PI=3.14159265;
    int radius;
}

File Rectangle.java;

public class Rectangle {
    double width=10.12;
    double height=5.7;
}

File ShapeTester.java;

public class ShapeTester {
    public static void main(String args[]){
        Circle x;//Instance variable
        Rectangle y;
        x=new Circle();
        y=new Rectangle();
        System.out.println(x+" "+y);
        System.out.println(x.radius);
        System.out.println(y.height);
    }
}

The value after @ is the storage address of the object referred to by x y.

Output results:
Circle@75b84c92 Rectangle@6bc7c054
0
5.7

Method

public class Circle {
    static double PI=3.14159265;
    int radius;
    //Declare the method for calculating the perimeter
    public double circumference(){
        return 2*PI*this.radius;
    }
}

Use this keyword to make it clearer where radius values come from. Since radius is an instance property in the class declaration, if the keyword this is not written in the above method, Java will automatically take the property value of its recipient object when the program runs, so in this case, the keyword this can be omitted from writing.

public class CircumferenceTester {
    public static void main(String args[]){
        Circle c1=new Circle();
        c1.radius=50;
        Circle c2=new Circle();
        c2.radius=10;
        double circum1=c1.circumference();
        double circum2=c2.circumference();
        System.out.println("circle 1:"+circum1);
        System.out.println("circle 2:"+circum2);
    }
}
Output results:
circle 1:314.159265
circle 2:62.831853

The main function begins with public static, which is the modifier of the method.

Let's first look at the static modifier, which makes a method global in scope. If we want to use this method, we don't need to create an instance, we can use it directly.

The keywords that modify access rights are public, private, protected. Classes, attributes, methods defined as publics can be accessed by any class. If they are private, they cannot be accessed by other classes. Protected applies to classes between inheritance relationships. Attributes and methods defined as protected can be accessed by subclasses. We will discuss more about parent and child classes later.

Class organization - package concept

The Java compiler generates a byte code file for each class, so classes with the same name may conflict. To resolve class name conflicts, Java provides a package mechanism to manage class name spaces.

Typically, related classes should be organized into the same package. Packages have the following main functions:
1) Organize related source code files together;
2) Class names can be the same in different packages to avoid name conflicts;
3) Provide package-level madness and access rights;

A Java compilation unit consisting of the following three parts:

  • The declaration of the owning package (omitted, the default package);
  • Declaration of an import package used to pour into an external class;
  • Declarations of classes and interfaces;

Packages and directories:

A package can contain several class files as well as several packages. Since Java uses the file system to store packages and classes, the class name is the file name, and the package name is the folder name, or directory name.

Introducing packages;

import PackageName;

In order to use the classes provided in other packages, you need to use the import statement to introduce the required classes.

Access control for class members;
There are several main considerations when declaring a class.

  • Keep it simple to use;
  • Easy to maintain;
  • Show only the necessary information to other classes. A good programming method generally does not allow other classes to directly access or modify instance variables of an object.

Access control for class members

  • Public: Components decorated with public are public, that is, they can be accessed by any other object (provided the class in which the class member resides has access rights);
  • Private: Members limited to private in a class can only be accessed by the class itself and are not visible outside the class;
  • Protected: Components modified with this keyword are protected and can only be accessed by instance objects of the same class and its subclasses;
  • No modifiers (default): public, private, protected qualifiers are not required to be written. If not, they indicate "friendly" and the corresponding components can be accessed by the various types contained in the package.

Program examples;

public class Circle {
    static double PI=3.14159265;
    private int radius;
    public double circumference(){
        return 2*PI*this.radius;
    }
}

Errors will be prompted when compiling;
java: radius is private access control in Circle
Since radius is declared private in the Circle class, it cannot be accessed directly in other classes.

If you want to allow other classes to access radius values, you need to declare the appropriate public methods in the Circle class. There are usually two typical methods for accessing attribute values, the get method and the set method.

get method

The function of the get method is to get the value of an attribute variable. For ease of memory and reading, the get method name begins with get, followed by the name of the instance variable. The get method generally has the following formats;

public <fieldType>get<FieldName>(){
	return <fieldName>;
}

For instance variable radius, declare its get method;

public int getRadius(){
	return radius;
}

set method

The function of the set method is to modify the value of an attribute variable. For ease of memory and reading, the set method name begins with "set" followed by the name of the instance variable. Set methods generally have the following formats;

public void set<FieldName>(<fieldType><paramName>){
	<fieldName>=<paramName>;
}

The set method for declaring the instance variable radius is as follows;

public void setRadius(int r){
	radius=r;
}

Use of the keyword this

If the formal parameter name is the same as the instance variable name, you need to add this keyword before the instance variable name. Otherwise, the system will treat instance variables as formal parameters.
In the set method above, if the form parameter is radius, the keyword this needs to be added before the member variable radius.

public class Circle {
    static double PI=3.14159265;
    int radius;
    public void setRadius(int radius){
        this.radius=radius;
    }

    public double circumference() {
        return 2*PI*radius;
    }
    public static void main(String args[]){
        Circle c1=new Circle();
        c1.setRadius(1);
        Circle c2=new Circle();
        c2.setRadius(10);
        double circum1=c1.circumference();
        double circum2=c2.circumference();
        System.out.println("circle 1:"+circum1);
        System.out.println("circle 2:"+circum2);
    }
}
Output:
circle 1:6.2831853
circle 2:62.831853

Objects and Initialization

When the object is generated, the system allocates memory space for the object and automatically invokes the construction method to initialize the instance variable. When the object is no longer in use, the system calls the garbage collector to reclaim its memory.

Construction method

The construction method is a special one. Every class in Java has a constructor that initializes a new object of that class. The construction method has the same name as the class name and does not return any data types. The system executes automatically when objects are generated.
1. The system provides default construction method;
The default construction method has no parameters and its body is empty.

class BankAccount{
    String ownerName="Tom";
    int accountNumber;
    float balance;
}
public class BankTester {
    public static void main(String args[]){
        BankAccount myAccount=new BankAccount();
        System.out.println("ownerName="+myAccount.ownerName);
        System.out.println("accountNumber="+myAccount.accountNumber);
        System.out.println("balance="+myAccount.balance);
    }
}
Output:
ownerName=Tom
accountNumber=0
balance=0.0

2. Custom construction methods and methods overload;
It is better to pass the initial value to the construction method when the object is generated and initialize the object with the desired value, which requires a custom construction method.

class BankAccount{
    String ownerName;
    int accountNumber;
    float balance;
    public BankAccount(String initName,int initAccountNumber,float initBalance){
        ownerName=initName;
        accountNumber=initAccountNumber;
        balance=initBalance;
    }
    public BankAccount(String initName,int initAccountNumber){
        ownerName=initName;
        accountNumber=initAccountNumber;
        balance=0.00f;
    }
}
public class BankTester {
    public static void main(String args[]){
        BankAccount myAccount=new BankAccount("Tom",1000,2000.00f);
        System.out.println("ownerName="+myAccount.ownerName);
        System.out.println("accountNumber="+myAccount.accountNumber);
        System.out.println("balance="+myAccount.balance);
        BankAccount myAccount1=new BankAccount("Bob",10000);
        System.out.println("ownerName="+myAccount1.ownerName);
        System.out.println("accountNumber="+myAccount1.accountNumber);
        System.out.println("balance="+myAccount1.balance);
    }
}
Output:
ownerName=Tom
accountNumber=1000
balance=2000.0
ownerName=Bob
accountNumber=10000
balance=0.0

Java allows multiple methods to have the same name. The same method name can be declared in different classes; The same method name can also be declared in the same class, but different parameter tables (different numbers and types of parameters) are required.
If there are two or more methods in a class with the same name but different parameter tables, this is called method overload. When a method is invoked, Java can tell which method to call from a different list of parameters.

3. Customize the construction method without parameters and this keyword;
When declaring a construction method, a good declaring practice is either not to declare a construction method, or if you declare a construction method, you usually declare at least two construction methods, one of which is a parameterless construction method.

class BankAccount{
    String ownerName;
    int accountNumber;
    float balance;
    public BankAccount(){
        this("",9999,0.0f);
    }
    public BankAccount(String initName,int initAccountNumber){
        this(initName,initAccountNumber,0.0f);
    }
    public BankAccount(String initName,int initAccountNumber,float initBalance){
        ownerName=initName;
        accountNumber=initAccountNumber;
        balance=initBalance;
    }
}
public class BankTester {
    public static void main(String args[]){

        BankAccount account1=new BankAccount();
        account1.ownerName="wangli";
        BankAccount account2=new BankAccount("Tom",1234,100.00f);
        BankAccount account3=new BankAccount("Bob",12345);
        System.out.println("ownerName="+account1.ownerName);
        System.out.println("accountNumber="+account2.accountNumber);
        System.out.println("balance="+account3.balance);
    }
}

Use this keyword to call another construction method in one construction method, which makes the code simpler and easier to maintain.

Memory Recycling Technology

When executing a construction method to generate an object, various system resources are required. When the generated object is no longer in use, it needs to be returned to the operating system to avoid resource leaks. Among various system resources, memory is the most commonly used. The Java runtime system periodically releases the memory used by unused objects through the garbage collector.

C releases memory by free, c++ by delete, and programmers can easily leak or even run out of memory if they forget to do so. There will be no memory leaks in Java, but for other resources, there is a possibility of leaks.

Every class in Java has a finalize() method to release resources, and the Java runtime system automatically calls the festive finalize() method to release system resources, such as closing open files or socket s, before the object is automatically garbage collected.

The method is declared in the following format;

protected void finalize() throws throwable

Finalize method in class java. It is declared in lang.Object, but nothing has been done. If a class needs to free resources other than memory, the finalize() method needs to be overridden in the class.

Keywords: Java Back-end Class

Added by ghjr on Wed, 15 Dec 2021 22:35:02 +0200