Re: [問題] 多形問題

看板java作者 (派立肯)時間11年前 (2012/10/28 20:27), 編輯推噓1(101)
留言2則, 2人參與, 最新討論串2/6 (看更多)
※ 引述《TWTRubiks (阿哲)》之銘言: : 目的,我想要把name和id宣告成private然後印出來(宣告成public就很簡單) Sometimes being simple doesn't mean being elegant. : 不過我想要宣告成private印出來(試了很多方法),都無法解決,想請問有甚麼比較好的解 : 決方法 : 我試過了用類似Getid(),不過還是不行因為還要Setid(),這樣會讓Person變得很雜 ^^^^^^^^^^^^^^^^^^^^^^ That's the problem of your thinking! In fact, if you use private filed it's very important that you need to have getters and setters. It's so-called "information hiding". When outside codes want to get the value of the variables, they only get the value of reference. There are huge differences between: student.name (without information hiding) student.getName() (with information hideing) When outside codes want to change the name temporarily, for example, in some situations you want to print out "王先生" instead of "王小明". //case without information hiding //what happens if you forget to change it back? String tempName = student.name; tempName = "王先生"; (student.name also changed) //case with information hiding //student.name is safe String tempName = student.getName(); tempName = "王先生"; (student.name never changes) A good programmer usually uses private, at least proteted, to secure the value of variables. When I studied JAVA programming in school, it would be zero mark if I wrote codes without information hiding... : 目前知道的解決方法,使用protected可以解決! : 但是想請問還有其他方法嗎?! : package aaa; : abstract class Person{ : private String name; : private int id; : abstract void printPerson(); : } : class Student extends Person{ : private double g1,g2,g3; : public Student(String name,int id,double g1,double g2,double g3){ : : //這裡我就不知道該怎麼打了,因為我式宣告成private,也以也不能打 ex. thid.id = id : this.g1=g1; this.g2=g2; this.g3=g3; use super() in the first line to pass values into parent class' constructor : } : public void printPerson(){ : double average,sum; : sum=g1+g2+g3; //sub-classes will inherit parent's method automatically sume = getG1() + getG2() + getG3(); : average=sum/3; : // 當然這裡也悲劇 : // System.out.println("姓名:"+name); getName() : // System.out.println("編號:"+getID()); : System.out.println("總分:"+sum); sum should be declared in Student class : System.out.println("平均:"+average); same as above : } : } : public class AAA { : /** : * @param args : */ : public static void main(String[] args) { : // TODO Auto-generated method stub : Student S=new Student("TWTRubiks",1100104105,96,99,60); : S.printPerson(); : } : } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 118.92.149.227 ※ 編輯: pelicanper 來自: 118.92.149.227 (10/28 20:28) ※ 編輯: pelicanper 來自: 118.92.149.227 (10/28 20:30) ※ 編輯: pelicanper 來自: 118.92.149.227 (10/28 20:31) ※ 編輯: pelicanper 來自: 118.92.149.227 (10/28 20:34)

10/30 16:00, , 1F
只+super()應該還是不能動吧?! 還是我理解力太差
10/30 16:00, 1F

10/30 16:49, , 2F
他不是說你還要有 getter & setter 方法嗎
10/30 16:49, 2F
文章代碼(AID): #1GZIIgHn (java)
討論串 (同標題文章)
本文引述了以下文章的的內容:
以下文章回應了本文
完整討論串 (本文為第 2 之 6 篇):
文章代碼(AID): #1GZIIgHn (java)