如何从超类与子类共享值

时间:2013-06-23 04:18:15

标签: java instance subclass superclass

我有一个名为Events的超类和两个名为talkworkshop的子类。

在超类中它有一个实例变量maxNumberOfParticupants

我想知道在创建一些谈话对象和研讨会对象时如何共享maxNumberOfParticipants

maxNumberOfParticpants的{​​{1}}为200,talk中的maxNumberOfParticipants为300; workshop最多参与者数量应该只能与talk个对象共享,talk仅限workshop个参与者的最大参与者数。

2 个答案:

答案 0 :(得分:1)

1-班级名称应为单数,首字母应为大写。 (比赛)

public class Event {

protected int maxNumberOfParticpants; // this level access is package and for childrens

public Event(int maxNumberOfParticipants){
this.maxNumberOfParticipants=maxNumberOfParticipants;
}

}

儿童

public class Talk extends Event {

public Talk(int maxNumberOfParticipants){
   super(maxNumberOfParticipants);
}


   public void someMethod(int max){
     if(this.maxNumberOfParticipants < max){
          // some code
     }
   }

}

public class Workshop extends Event{

public Workshop(int maxNumberOfParticipants){
   super(maxNumberOfParticipants);
}

}

答案 1 :(得分:0)

class Event {
    protected int  maxNumberOfParticipants;
    public Event(int number) {
       this.maxNumberOfParticipants = number;
    }

    public int getMaxNumberPariticipants() {
       return maxNumberOfParticipants;
    }

}

class Talk extend Event {
    Talk(int number) {
       super(number)
     }
}


class Workshop extend Event {
    Workshop(int number) {
       super(number)
     }
}


public static void main(String a[]) {
    Event talk = new Talk(200);
    Workshop talk = new Workshop(300);
    System.out.println(talk.getMaxNumberPariticipants()) ---> 200
    System.out.println(workshop.getMaxNumberPariticipants()) ---> 300
}