本帖最后由 xiao7181jun 于 2015-5-8 23:47 编辑
- class Person {
- public String hair;
- public String skin;
- private String sex;//私有化变量,不可直接被调用。需要在本类设置公共的访问方法。
- private int height;
- public Person() {}//无参构造函数,作用是初始化对象的成员变量。当定义了有参变量的话必须要手动添加无参构造函数。
- //因为手动设置了有参函数的话系统就不会再创建默认的无参函数了。
-
- public Person(int height,String sex) { //这是有参构造函数。
- this.height = height;
- this.sex = sex;
- }
- public void show() { //本类中的方法是可以访问本类的私有变量的,利用这个公共的方法来赋值私有变量。
- System.out.print(sex+","+height);
- }
-
- /* public void setPerson(String sex,int height) { //用Person中的方法,把Student里参数赋的值 利用this 赋给Person的私有成员变量。
- this.sex = sex;
- this.height = height;
- }
- public String getSex() { //把sex值 返回给调用者
- return sex;}
- public int getHeight() {
- return height;}
- */
- }
- class School {
- public String teach;//教育的意思
- public String study;
- private String name;
- private int tuition; //这个单词不熟(学费的意思),导致下面的单词拼错!!耽误时间!!
- public School() {}
- public School(String name,int tuition) {
- this.name = name;
- this.tuition = tuition;
- }
- public void show() {
- System.out.print(name+","+tuition);
- }
- /* public void setSchool(String name,int tuition) {
- this.name = name;
- this.tuition = tuition;
- }
- public String setName() {
- return name;}
- public int setTuition() {
- return tuition;}
- */
- }
- class Student extends Person { //继承Person的子类
-
- public Student() {}
- public Student(int height,String sex) {
- super(height,sex);
- }
- //在父类中也建了一个方法名字叫show,然后出现问题显示NULL(空值),
- //原来是这句话搞的鬼!!子类里的方法发生的“重写”,把我想调用的父类Person里的值给覆盖掉了,
- //显示了这个当时还没有被没赋值的“hair”!!!
- //public void show() {
- //System.out.println(hair);}
- }
- class CaiMao extends School { //继承School的子类
- public CaiMao() {}
- public CaiMao(String name,int tuition) {
- super(name,tuition);
- }
- }
- class ExtendsDemo2 { //测试类
- public static void main(String[] args) {
- /*
- //方式一:
- Student s = new Student(); //创建 对象
- s.hair ="黄头发"; //赋值
- s.skin ="黄皮肤";
- s.setPerson("男",158); //在对象Student下的赋值都需要加 s. 没注意爆了好多错。
- System.out.println(s.hair+","+s.skin+","+s.getHeight()+","+s.getSex()); //在子类对象中输出其父类的私用的与公共的参数。
- s.show();
- JiSuanJi j = new JiSuanJi();
- j.teach = "教育";
- j.study = "学习";
- j.setSchool("计算机学院",8888);
- System.out.println(j.teach+","+j.study+","+j.setTuition()+","+j.setName());
- */
- //方式二:
- Student s1 = new Student(188,"男");
- s1.show();
- s1.hair = "黄头发";
- s1.skin = "黄皮肤";
- System.out.println(","+s1.hair+","+s1.skin);
-
- CaiMao t1 = new CaiMao("财贸学院",8888);
- t1.show();
- t1.teach = "教育";
- t1.study = "学习";
- System.out.println(","+t1.teach+","+t1.study);
- }
-
- }
复制代码 |
|