Last active
April 2, 2017 02:16
-
-
Save goldcode88/3355a3ce66df182610309f7cc859cb29 to your computer and use it in GitHub Desktop.
问题1:如何重载toString
1.toString是Objects的内部函数,不需要显式继承就可以覆盖,当然显式继承也可以。
参见:http://www.geeksforgeeks.org/overriding-tostring-method-in-java/
问题2:
2.为何重载了toString,println就会去调用它?
参见:http://stackoverflow.com/questions/29318996/the-connection-between-system-out-println-and-tostring-in-java
...calls at first String.valueOf(x) to get the printed object's stri…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // file name: Main.java | |
| class Complex { | |
| private double re, im; | |
| public Complex(double re, double im) { | |
| this.re = re; | |
| this.im = im; | |
| } | |
| } | |
| // Driver class to test the Complex class | |
| public class Complex_test1 { | |
| public static void main(String[] args) { | |
| Complex c1 = new Complex(10, 15); | |
| System.out.println(c1); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // file name: Main.java | |
| class Complex extends Object{ | |
| private double re, im; | |
| public Complex(double re, double im) { | |
| this.re = re; | |
| this.im = im; | |
| } | |
| /* Returns the string representation of this Complex number. | |
| The format of string is "Re + iIm" where Re is real part | |
| and Im is imagenary part.*/ | |
| @Override | |
| public String toString() { | |
| return String.format(re + " + i" + im); | |
| } | |
| } | |
| // Driver class to test the Complex class | |
| public class Complex_test2 { | |
| public static void main(String[] args) { | |
| Complex c1 = new Complex(10, 15); | |
| System.out.println(c1); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment