[問題] 多形問題

看板java作者 (阿哲)時間13年前 (2012/10/28 16:15), 編輯推噓5(504)
留言9則, 5人參與, 最新討論串1/6 (看更多)
目的,我想要把name和id宣告成private然後印出來(宣告成public就很簡單) 不過我想要宣告成private印出來(試了很多方法),都無法解決,想請問有甚麼比較好的解 決方法 我試過了用類似Getid(),不過還是不行因為還要Setid(),這樣會讓Person變得很雜 目前知道的解決方法,使用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; } public void printPerson(){ double average,sum; sum=g1+g2+g3; average=sum/3; // 當然這裡也悲劇 // System.out.println("姓名:"+name); // System.out.println("編號:"+getID()); System.out.println("總分:"+sum); System.out.println("平均:"+average); } } 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: 203.64.91.231

10/28 16:22, , 1F
name 跟 id 改為 protected 應該是你要的
10/28 16:22, 1F

10/28 16:27, , 2F
super?
10/28 16:27, 2F

10/28 16:34, , 3F
super我試過了~! 沒辦法, protected沒教過~!我google
10/28 16:34, 3F

10/28 16:37, , 4F
看看
10/28 16:37, 4F
L大大~! 改成 protected 的確解決了~! 不過還有其他的方法可以解決嗎?! 不過我猜 protected 應該是最簡單的方法了~! ※ 編輯: TWTRubiks 來自: 203.64.91.231 (10/28 16:46)

10/28 18:00, , 5F
protected吧!不然getID(),getName(),加super()
10/28 18:00, 5F

10/28 18:26, , 6F
重點是... 為甚麼一開始要設 private?
10/28 18:26, 6F

10/28 18:27, , 7F
如果可以亂改,那加 getter/setter 也可以?
10/28 18:27, 7F

10/28 21:03, , 8F
protected 這個關鍵字正是為了你這個情形才有的
10/28 21:03, 8F

10/28 21:06, , 9F
這個宣告代表這些屬性子類別有權存取 正是你所想要的情形
10/28 21:06, 9F
文章代碼(AID): #1GZEcFna (java)
討論串 (同標題文章)
文章代碼(AID): #1GZEcFna (java)