Java Study Notes 4-basic concepts of classes and objects (2), learning notes 4 --

Source: Internet
Author: User

Java Study Notes 4-basic concepts of classes and objects (2), learning notes 4 --

URL: http://www.cnblogs.com/archimedes/p/java-study-note4.html.

1. object initialization and collection

Object initialization

When an object is generated, the system allocates memory space for the object and automatically calls the constructor to initialize the instance variables.

Object recycling

When an object is no longer in use, the system calls the garbage collection program to recycle the memory it occupies.

Constructor

  • A special method with the same name as a class

  • Used to initialize objects

  • Every class in Java has a constructor to initialize a new object of the class.

  • If no constructor class is defined, the system automatically provides the default constructor.

Features of Constructor
  • The method name is the same as the class name.

  • No response type. The modifier void cannot exist.

  • Usually declared as public)

  • Can have any number of parameters

  • The main function is to complete object initialization.

  • Cannot be explicitly called in a program

  • When an object is generated, the system automatically calls the constructor of this class to initialize the newly generated object.

Default Construction method provided by the system

If no constructor is declared in the class declaration, the Java compiler provides a default constructor. The default constructor has no parameters and its method body is empty; when you use the default constructor to initialize an object, if no initial value is assigned to the instance variable in the class declaration, the object's attribute value is zero or empty.

Example: declare a bank account and test code

public class BankAccount{    String  ownerName;    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);    }}
Running result:

OwnerName = null

AccountNumber = 0

Balance = 0.0

Custom constructor methods and method Overloading

You can send an initial value to the constructor when generating an object and use the expected value to initialize the object.

Constructor can be overloaded. the constructor's overloading is consistent with the method's overloading.

There are two or more methods in a class with the same name, but the parameter table is different. This is called method overload. When calling a method, Java can identify which method should be called through different parameter lists for BankAccount to declare a constructor with three parameters

public BankAccount(String initName, int initAccountNumber, float initBalance) {         ownerName = initName;         accountNumber = initAccountNumber;         balance = initBalance;}

Assuming that the initial balance of a new account can be 0, you can add a constructor with two parameters.

public BankAccount(String initName, int initAccountNumber) {        ownerName = initName;        accountNumber = initAccountNumber;        balance = 0.0f;    }

Custom construction method without Parameters

The construction method without parameters is very important to the declaration of its subclass. If there is no constructor without parameters in a class, the constructor must be declared when its subclass is declared. Otherwise, an error occurs during the initialization of the subclass object.

When declaring a constructor, a good habit of declaring a constructor is to not declare a constructor. If declaring a constructor, declare at least one constructor without parameters.

Construct a Bush class with two parameter constructor methods:
class Bush {  Bush(int i) {}  Bush(double d) {} }

If you write: new Bush (); the compiler will tell you that the corresponding constructor cannot be found.

Note:

If you do not declare any constructor when declaring a class, the system will assign such a default (No parameter) constructor. However, as long as the user declares the constructor method, the system does not assign the default constructor method even if no constructor is declared.

For example, create a Tree class with two constructor methods, one with parameters and one without parameters.

import java.util.*;class Tree {     int height;    Tree() {         prt("Planting a seedling");         height = 0;     }    Tree(int i) {         prt("Creating new Tree that is "+ i + " feet tall");        height = i;    }    void info() {        prt("Tree is " + height + " feet tall");    }    void info(String s) {        prt(s + ": Tree is " + height + " feet tall");     }    static void prt(String s) {        System.out.println(s);       }} 

Test Tree:

public class javatest {    public static void main(String[] args) {        for(int i = 0; i < 5; i++) {            Tree t = new Tree(i);            t.info();            t.info("overloaded method");        }        new Tree();    }}

Test results:

Creating new Tree that is 0 feet tall
Tree is 0 feet tall
Overloaded method: Tree is 0 feet tall
Creating new Tree that is 1 feet tall
Tree is 1 feet tall
Overloaded method: Tree is 1 feet tall
Creating new Tree that is 2 feet tall
Tree is 2 feet tall
Overloaded method: Tree is 2 feet tall
Creating new Tree that is 3 feet tall
Tree is 3 feet tall
Overloaded method: Tree is 3 feet tall
Creating new Tree that is 4 feet tall
Tree is 4 feet tall
Overloaded method: Tree is 4 feet tall
Planting a seedling

Use of the this keyword:

  • You can use the this keyword to call another constructor in a constructor.

  • Code is simpler and easier to maintain

  • Generally, a constructor with a relatively small number of parameters is used to call the constructor with the largest number of parameters.

Use the this keyword to modify the constructor of the BankAccout class without parameters and two parameters:

public BankAccount() {         this("", 999999, 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; }
2. Memory Recovery Technology

When an object is no longer used in a program, it becomes a useless object. The current code segment does not belong to the scope of the object and the object reference value is null.

During Java runtime, the system periodically releases the memory used by useless objects through the garbage collector.

During Java runtime, the system automatically calls the finalize () method of the object before automatic garbage collection of the object.

Garbage Collector

Automatically scans the dynamic memory area of the object and marks the objects that are no longer in use for garbage collection.

Run as a thread, usually asynchronously when the system is idle

When the System memory is used up or the program calls System. gc () for garbage collection, it runs in sync with the System.

Finalize () method

  • Declared in the class java. lang. Object, so every class in Java has this method

  • Used to release system resources, such as disabling open files or sockets.

  • Declaration format

protected void finalize() throws throwable

If a class needs to release resources other than memory, the finalize () method must be rewritten in the class.

Example:

Perform a series of modifications and tests on the bank account BankAccount:

  • Declare the BankAccount class

  • Declare toString () method

  • Method of declaring deposit and withdrawal

  • Use DecimalFormat class

  • Declare a class method to generate a special instance

  • Declare class variables

  • Including status, constructor, get method, and set Method
public class BankAccount{    private String ownerName;     private int accountNumber;     private float balance;         public BankAccount() {             this("", 0, 0);     }            public BankAccount(String initName, int initAccNum, float initBal) {            ownerName = initName;         accountNumber = initAccNum;         balance = initBal;     }           public String getOwnerName()  { return ownerName; }         public int getAccountNumber() { return accountNumber; }         public float getBalance()  { return balance; }         public void setOwnerName(String newName) {         ownerName = newName;    }             public void setAccountNumber(int newNum) {         accountNumber = newNum;     }             public void setBalance(float newBalance) {         balance = newBalance;     } }

Declare test class AccountTester

public class AccountTester {     public static void main(String args[]) {         BankAccount anAccount;         anAccount = new BankAccount("ZhangLi", 100023,0);         anAccount.setBalance(anAccount.getBalance() + 100);                 System.out.println("Here is the account: " + anAccount);                 System.out.println("Account name: " + anAccount.getOwnerName());                 System.out.println("Account number: " + anAccount.getAccountNumber());                 System.out.println("Balance: $" + anAccount.getBalance());    } }
Test results:

Here is the account: BankAccount @ 372a1a

Account name: ZhangLi

Account number: 100023

Balance: $100.0

Declare toString () method

Convert the object content to a string

All classes in Java have a default toString () method. The method body is as follows:

getClass().getName() + '@' +  Integer.toHexString(hashCode())

The following two lines of code are equivalent:

System.out.println(anAccount);System.out.println(anAccount.toString());

If you need special conversion functions, you must rewrite the toString () method by yourself.

Description of the toString () method

  • Must be declared as public

  • The return type is String.

  • The method name must be toString and there is no Parameter

  • Do not use the output method System. out. println () in the method body ()

Add your own toString () method to the BankAccount class
public String toString() {    return("Account #" + accountNumber + " with balance $" + balance);}
References:

Java programming-Tsinghua University

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.