java – 在下面的代码中使用toString()方法的目的是什么?
发布时间:2020-12-15 02:07:23 所属栏目:Java 来源:网络整理
导读:参见英文答案 How to override toString() properly in Java?????????????????????????????????????11个 根据我的理解,toString()方法允许转换类型示例:int x = 5,sys ….(x.toString())并将5打印到控制台.但是,与我的代码相反,这样做的好处/弊端是什么? (
参见英文答案 >
How to override toString() properly in Java?????????????????????????????????????11个
根据我的理解,toString()方法允许转换类型示例:int x = 5,sys ….(x.toString())并将5打印到控制台.但是,与我的代码相反,这样做的好处/弊端是什么? (不是说我的更好,我真的很好奇) 这是我的代码: public class GitFiddle { //Initalize class variables. private String guitarMake; private String guitarModel; private int numOfStrings; private String notes; private int jumboFrets; private String neckType; private String fingerBoard; private String humPickUps; private boolean tuned; //A constructor that has specific variables assigned to it. public GitFiddle (String guitarMake,String guitarModel,int numOfStrings,String notes,int jumboFrets,String neckType,String fingerBoard,String humPickUps,boolean tuned) { this.guitarMake = guitarMake; this.guitarModel = guitarModel; this.numOfStrings = numOfStrings; this.notes = notes; this.jumboFrets = jumboFrets; this.neckType = neckType; this.fingerBoard = fingerBoard; this.humPickUps = humPickUps; this.tuned = tuned; } //Created the output that will be displayed to the user. public String output() { return "My guitar is an " + guitarMake + "," + " " + guitarModel + " which is a " + numOfStrings + "-string,electric guitar." + "nThe standard tuning for this guitar is as follows(from low to high): " + notes + "." + "nIt has " + jumboFrets + " jumbo frets on a " + neckType + ",a " + fingerBoard + " fingerboard and pearl,dot inlays." + "nIt also has dual " + humPickUps + " humbucker pickups which is perfect for some sweet metal action!" + "nIs this 7-string beauty tuned up and ready to play?: " + tuned + "nAre you ready?"; } public static void main(String args[]) { //Create an instance of household item method. GitFiddle guitar = new GitFiddle ("Ibanez","S-7 320 EX",7,"B E A D G B E",22,"Wizard,W-7 II neck","rosewood","EMG 81 85",true); //Output the status of the household item. System.out.println(guitar.output()); } } 解决方法
将public String output()更改为public String toString().你已经建立了它,只是给它另一个名字.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |