Java Learning Notes Basic concepts of 4--classes and objects (2)

Source: Internet
Author: User

This article address: http://www.cnblogs.com/archimedes/p/java-study-note4.html, reprint please indicate source address.

1. Object initialization and Recycling

Object initialization

When the system generates an object, it allocates memory space for the object and automatically calls the construction method to initialize the instance variable.

Object Recycling

object is no longer in use, the system calls the garbage collector to reclaim the memory it consumes

Construction method

    • A special method with the same name as a class

    • Used to initialize an object

    • Each class in Java has a constructor method that initializes a new object of the class

    • There is no class that defines the constructor method, and the system automatically provides the default construction method

Characteristics of the construction method
    • The method name is the same as the class name

    • There is no return type, and the modifier void cannot have

    • Usually declared public

    • can have any number of parameters

    • The main function is to complete the initialization of the object

    • cannot be explicitly called in a program

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

Default construction method provided by the system

If the constructor method is not declared in the class declaration, the Java compiler provides a default construction method, the default constructor method has no parameters, the method body is empty, and when the object is initialized with the default constructor method, if the instance variable is not assigned an initial value in the class declaration, the object's property values are zero or empty

Example: Declaring a bank account number class and testing code

 Public classbankaccount{String ownername; intAccountNumber; floatbalance;} Public classbanktester{ Public Static voidMain (String args[]) {BankAccount MyAccount=NewBankAccount (); System.out.println ("Ownername=" +myaccount.ownername); System.out.println ("Accountnumber=" +myaccount.accountnumber); System.out.println ("Balance=" +myaccount.balance); }}
Operation Result:

Ownername=null

Accountnumber=0

balance=0.0

Custom Construction methods and method overloads

You can pass the initial value to the construction method when the object is generated, and initialize the object with the desired value.

Construction methods can be overloaded, the overloads of the constructor methods and the overloads of the methods are consistent

There are two or more methods of the same name in a class, but the parameter table is different, and this is called a method overload. In a method invocation, Java can identify which method should be called by using the parameter list to declare a constructor with three arguments for BankAccount

 Public int float initbalance) {         = initname;          = Initaccountnumber;          = initbalance;}

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

 Public int Initaccountnumber) {        = initname;         = Initaccountnumber;         = 0.0f;    }

Custom non-parametric construction methods

The construction method of the parameterless is important for the declaration of its subclasses. If there is no parameterless constructor in a class, the constructor must be declared when its child class is declared, otherwise an error occurs during initialization of the subclass object

When declaring a construction method, a good declaration of habit is not to declare a construction method, or at least to declare a non-parametric construction method if declared

To build a Bush class, there are two parameters to construct the method:
class Bush {bush (int  i) {} Bush (double  d) {}}

If write: New Bush (); The compiler is going to tell you that you can't find the corresponding construction method

Description

When a user makes a class declaration, if no constructor method is declared, the system assigns a default (no argument) constructor to this class. However, as long as the user declares the constructor method, the system no longer assigns the default construction method even if no argument is declared.

Example: Create a tree class with two constructor methods, one with a parameter and one without a parameter.

ImportJava.util.*;classTree {intheight; Tree () {PRT ("Planting a seedling"); Height= 0; } Tree (inti) {prt ("Creating new Tree is" + i + "feet tall"); Height=i; }    voidinfo () {PRT ("Tree is" + height + "feet tall"); }    voidinfo (String s) {PRT (S+ ": Tree is" + height + "feet tall"); }    Static voidprt (String s) {System.out.println (s); }} 

Test the Tree class:

 Public class javatest {    publicstaticvoid  main (string[] args) {        for (int i = 0; i < 5; i++) {            new  Tree (i);            T.info ();            T.info ("overloaded method");        }         New Tree ();}    }

Test results:

Creating New Tree is 0 feet tall
Tree is 0 feet tall
overloaded Method:tree is 0 feet tall
Creating New Tree is 1 feet tall
Tree is 1 feet tall
overloaded Method:tree is 1 feet tall
Creating New Tree is 2 feet tall
Tree is 2 feet tall
overloaded Method:tree is 2 feet tall
Creating New Tree is 3 feet tall
Tree is 3 feet tall
overloaded Method:tree is 3 feet tall
Creating New Tree 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 invoke additional construction methods in a constructor method

    • The code is more concise and easier to maintain.

    • A construction method that calls the maximum number of parameters by using a construction method with a lower number of arguments

Using the This keyword, modify the constructor for no parameters and two parameters in the Bankaccout class:

 public   BankAccount () { this  ("", 999999, 0.0f public  BankAccount (String initname, int   this  (Initname, initaccountnumber, 0.0f);  public  BankAccount (String initname,  int   Initaccountnumber,  float  Span style= "color: #000000;"          > Initbalance) {ownername  = Initname;          AccountNumber  = Initaccountnumber; Balance  = Initbalance;}  
2. Memory Recovery Technology

When an object is no longer used in the program, it becomes a useless object, the current code fragment is not in the scope of the object, the object's reference is assigned to NULL

The Java runtime system periodically frees memory used by useless objects through the garbage collector

The Java runtime system automatically calls the Finalize () method of an object before it is automatically garbage collected

Garbage collector

Automatically scans the dynamic memory area of an object, marking objects that are no longer being used for garbage collection

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

Runs synchronously with the system when the system is running out of memory or calls to System.GC () in the program require garbage collection

Finalize () method

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

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

    • Declaration format

protected void throws Throwable

If a class needs to free resources other than memory, you need to override the Finalize () method in the class

Application Examples:

A series of modifications and tests are made to the bank account class BankAccount:

    • Declaring the BankAccount class

    • Declares the ToString () method

    • Declaring deposit and Withdrawal methods

    • Using the DecimalFormat class

    • Declaring a class method to generate a special instance

    • Declaring class variables

    • Including state, construction method, get method and set method
 Public classbankaccount{PrivateString ownername; Private intAccountNumber; Private floatbalance;  PublicBankAccount () { This("", 0, 0); }             PublicBankAccount (String Initname,intInitaccnum,floatInitbal) {ownername=Initname; AccountNumber=Initaccnum; Balance=Initbal; }            PublicString Getownername () {returnownername;}  Public intGetaccountnumber () {returnAccountNumber;}  Public floatGetBalance () {returnbalance;}  Public voidsetownername (String newName) {ownername=NewName; }              Public voidSetaccountnumber (intnewnum) {AccountNumber=Newnum; }              Public voidSetbalance (floatnewbalance) {Balance=newbalance; } }

Declaring the test class Accounttester

 Public classAccounttester { Public Static voidMain (String args[]) {BankAccount anaccount; Anaccount=NewBankAccount ("Zhangli", 100023,0); Anaccount.setbalance (Anaccount.getbalance ()+ 100); System.out.println ("Here's 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 are the account: [email protected]

Account Name:zhangli

Account number:100023

Balance: $100.0

Declares the ToString () method

Convert the contents of an object to a string

All classes in Java have a default ToString () method with the following method body:

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 a special conversion function, you need to override the ToString () method yourself

A few notes of the toString () method

    • Must be declared as public

    • The return type is string

    • The name of the method must be ToString, and there is no parameter

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

Add your own ToString () method for the BankAccount class
 Public String toString () {    return(' account # ' + AccountNumber + "with balance $" + balance);}
Resources:

"Java Programming"--Tsinghua University

Java Learning Notes Basic concepts of 4--classes and objects (2)

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.