when I first started to write software in Java, no matter know JavaBean, there is no habit of rewriting ToString (), except the Great God, The book or the teacher may have mentioned to rewrite ToString (), but it is difficult for beginners to notice this operation.
What's the use of rewriting ToString ()? The greatest use is the convenience of debugging, System.out.println () is a very common debugging method. For example, there is a JavaBean class person, there are many attributes, such as name, age and gender, when you need to print view properties, the general beginner often a line to print a property, and lazy to add hint string, when the code volume increases, logic becomes complex, such debugging will try to become bloated code, and will give oneself debugging to bring trouble, repeated write hint string cumbersome, forget to print which property and many of the same type of printing lead to confusion and other problems can easily make oneself irritable.
Therefore, when writing JavaBean classes or similar classes, you may wish to rewrite ToString () to present the class and its attributes in a clear and concise manner, so that it is convenient for others.
Here is a sample code:
/*** Rewrite ToString ()*/ Public classTest { Public Static voidMain (string[] args) { person person=NewPerson ("Student a", 20,true); /*System.out.println ("Name:" + person.getname ()); System.out.println ("Age:" + person.getage ()); System.out.println ("Isboy:" + person.isboy ());*/System.out.println (person); }}classPerson {PrivateString name; Private intAge ; Private BooleanBoy ; PublicPerson (String name,intAgeBooleanBoy ) { This. Name =name; This. Age =Age ; This. Boy =Boy ; } @Override PublicString toString () {return"Person [" + "Name:" + name + "; Age: ' + age + '; Isboy: "+ Boy +"] "; } /*** How to quickly generate getter/setter under eclipse * not often used * Fast key: * 1. ALT + SHIFT + S "* 2. R * 3. TAB * 4. Enter * 5. SHIFT + TAB * 6. Enter*/ PublicString GetName () {returnname; } Public intGetage () {returnAge ; } Public voidSetage (intAge ) { This. Age =Age ; } Public BooleanIsboy () {returnBoy ; } Public voidSetboy (BooleanBoy ) { This. Boy =Boy ; } Public voidsetName (String name) { This. Name =name; }}
Rewrite ToString ()