作者pelicanper (派立肯)
看板java
标题Re: [问题] 多形问题
时间Sun Oct 28 20:27:18 2012
※ 引述《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)
1F:推 TWTRubiks:只+super()应该还是不能动吧?! 还是我理解力太差 10/30 16:00
2F:→ qrtt1:他不是说你还要有 getter & setter 方法吗 10/30 16:49