12-20java Object-oriented class & wrapper class & Anonymous inner class

Source: Internet
Author: User

1.Object Class
In Java development, all classes exist in the form of inheritance, and if a class does not explicitly indicate which class is inherited, it inherits the object class by default.

For example

Class Person {}

The above code defines Objectby default, and its complete representation is:

Class Person extends object{}

In the JDK document,api-> index->java.lang->object looks for the Object class.

A complete class should be a method of covering the Object class, and here are some important methods to explain.

1.1public String toString ()

Called when the object is printed.

For example

Class person//defines the person class, which actually inherits the object class {}public class Testobject {public static void main (string[] args) {person per = NE w person (); System.out.println (per);}}

The result prints the address of per

Because person is inheriting the object class, All methods of the object class (friendly and Public ) can be used. Then use toString()

Class person//defines the person class, which actually inherits the object class {}public class Testobject {public static void main (string[] args) {person per = NE w person (); System.out.println (Per.tostring ());}}

If the results are identical, the toString() method must be called when printing, which is called by default. You can use this method to complete the output of the information.

Class person//defines the person class, which actually inherits the object class {private String name;p rivate int;p ublic person (String name, int age) {THIS.N Ame =name; this.age = age;} Public String toString () {return name: "+ THIS.name +", Age: "+ This.age;}} public class Testobject {public static void main (string[] args) {person per = new Person ("Tyrion", 24); System.out.println ("Use ToString () method" + per.tostring ()); System.out.println ("Do not use ToString () method" + per);}}

So in the future to print the output object information, directly overwrite the toString method, directly use the object can be printed.

1.2public boolean equals (Object obj)

Equals() completes the comparison of object content that was previously used in the String class.

Class person//defines the person class, which actually inherits the object class {private String name;p rivate int;p ublic person (String name, int age) {THIS.N Ame =name; this.age = age;} Public A Boolean equals (Object obj) {if (this = = obj)//Description Two classes occupy an address {return true;} if (obj instanceof person)  //must be guaranteed to be a class to be compared, cannot be compared because two object properties are the same as {//object is the parent class, which uses to compare attributes in the parent class, need to transform person per = (person) obj; if (this.name.equals (per.name) && this.age = = per.age) {return true;} else {return false;}} Else{return false;}} Public String toString () {return name: "+ THIS.name +", Age: "+ This.age;}} public class Testobject {public static void main (string[] args) {person per1 = new Person ("Tyrion", 24); Person per2 = new Person ("Tyrion", 24); System.out.println (Per1.equals ("")); System.out.println (Per1.equals (Per2));}}

Program Note:

In the overwrite process, objectis used,because object is the parent of all classes, so the first thing to do is to make a instanceof judgment, and then to make a downward transition , the Object class becomes a subclass in order to continue the comparison.

Program Development:

This program illustrates the problem--you can define different subclasses ( as opposed to Object ), they may need to compare, You can inherit the method directly.

But here's the problem:

Class person//defines the person class, which actually inherits the object class {private String name;p rivate int;p ublic person (String name, int age) {THIS.N Ame =name; this.age = Age;}} public class Testobject {public static void main (string[] args) {person per1 = new Person ("Tyrion", 24); Person per2 = new Person ("Tyrion", 24); System.out.println (Per1.equals (Per2));}}
False

Class person//defines the person class, which actually inherits the object class {private String name;p rivate int;p ublic person (String name, int age) {THIS.N Ame =name; this.age = Age;}} public class Testobject {public static void main (string[] args) {person per1 = new Person ("Tyrion", 24); Person per2 = new Person ("Tyrion"), Object obj1 = per1;object obj2 = per2; System.out.println (Obj1.equals (Per1));}}
True

ObjectClass ofequalsmethod implements the equality relationship that is most likely to vary on an object, that is, for any non-null reference valuexand they, when and only ifxand theyThis method returns when the same object is referencedtrue(x = = yhas a valuetrue).
A first example PersonInheritanceequalsMethod,No rewrite,So whether the reference to the object is the same,-->Same astruenot the sameFALSEP1,P2's AllNewcreated by,allocate two different spaces in the heap,sofalse

The second example is obj1.equals (per1), which compares obj1 and per1,object obj1 = per1; when passing the Per1 value is passed to the Obj1, so two objects point to the same piece of space , return true;

Because object is the parent class for all classes, objects of all classes can be received using Object , and Object can receive arbitrary The reference data type .

Using Object for interface reception

Interface A{public abstract String getInfo ();} Class B implements a//b classes Implement Interface A{public String GetInfo () {return "Hello World  ";}}  public class Testobject {public static void main (string[] args) {A A = new B ();//Instantiate interface Object obj = a;//Use object to receive, up transformation A x = (A) obj;//downward transition System.out.println (X.getinfo ());}}

Array Reception using Object

public class Testobject {public static void main (string[] args) {int arr[] = {1,3,4,5};//Definition array Object obj = Arr;print (obj);} public static void Print (Object obj) {if (obj instanceof int[])//Determines whether the integer array {int x[] = (int[]) obj;//down transforms the object into an integer array for (int I=0;i<x.length; ++i) {System.out.println (x[i]);}}}
1.3Summary

1. Object is the parent class of all classes, as long as the reference data type can be passed using Object

2, the object must be transferred upward before the transformation, and to use instanceof to judge

2. Packing class

put a thought into Java: Everything is the object. Then the basic data type is not an object, wrapping 8 basic data types into classes.

8 types of packaging

For the number class

Number is a Direct subclass of Object, which changes the contents of a digital wrapper class into a basic data type (unboxing).

Boxing : Changing the base data type into a wrapper class

unpacking : Turning wrapper classes into basic data types

Take Integer as an example:

public Integer (int value)

public class TestWapper1 {public static void main (string[] args) {integer i = new Integer (one-by-one);//integer class constructor, equivalent to subclass instantiation, Loaded Box number num = i;     Pass int x = Num.intvalue () up;//Call method of number class, unpacking}}

Take Float for example:

public class TestWapper2 {public static void main (string[] args) {float f = new float (11.1f);//The construction method of float class, equivalent to subclass instantiation, boxed FL Oat x = F.floatvalue ();//Call method of number class, unpacking}}

Before JDK1.5 , the wrapper class of the program could not directly use "+-*/" because they are all a class. After that, the function of the wrapper class is changed, the automatic packing and unpacking is added, and the packing class can be used for digital operation.

public class TestWapper3 {public static void main (string[] args) {Integer i = 30;//automatically boxed into integerint j = i;//auto-unpacking into int}}

In the wrapper class, there is a big feature--the string becomes the specified data type.

In the integer

parseint

public static int parseint (String s) throws NumberFormatException

Parsefloat

public static int parsefloat (String s) throws NumberFormatException

The string must consist of a number, and the feature of the method--the string can be passed through the input.

public class TestWapper3 {public static void main (string[] args) {string str1 = "300";//The string must be all numeric string str2 = "300.33" ;//The string must be all numeric int i = Integer.parseint (str1); float j = float.parsefloat (STR2); System.out.println ("The exponent of the whole number:" + i + "*" + i + "=" + I*i); System.out.println ("The Powers of the decimal:" + j + "*" + j + "=" + J*j);}}

public class TestWapper3 {public static void main (string[] args) {string str1 = new string (args[0]);//The string must be all numeric string St r2 = new string (args[1]);//The string must be all numeric int i = Integer.parseint (str1); float j = float.parsefloat (STR2); System.out.println ("The exponent of the whole number:" + i + "*" + i + "=" + I*i); System.out.println ("The Powers of the decimal:" + j + "*" + j + "=" + J*j);}}
2. Anonymous inner class

Definition: A class is used only once in the entire operation, defined as an anonymous inner class, developed on the basis of abstract classes and interfaces.

Interface  a{public abstract void print ();//define internal abstract method}class B implements a{public void print () {System.out.println (" Hello java ");}} Class C{public void Fun1 () {this.fun2 (new B ());//pass an instance of B, call the interface method}public void Fun2 (a a) {A.print ();}} public class Noname_inner {public static void main (string[] args) {c C =new C (); C.fun1 ();}}

If at this point the classB is only used once, then there is no need to define a class separately.

Interface  a{public abstract void print ();//define internal abstract method}class c{public void Fun1 () {this.fun2 (new A () {public void print ( {System.out.println ("Hello java");}); /Pass An instance of B, call the interface method}public void Fun2 (a a) {A.print ();}} public class Noname_inner2 {public static void main (string[] args) {c C =new C (); C.fun1 ();}}

I wish you all a healthy and happy.









12-20java Object-oriented class & wrapper class & Anonymous inner class

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.