Andrew
Andrew

Reputation: 1

How to share value from superclass with subclass

I have one superclass named Events and 2 subclass named, talk and workshop.

In the superclass it has a instance variable maxNumberOfParticupants.

I would like to know how to share the maxNumberOfParticipants when I create a few talk objects and workshop object.

The maxNumberOfParticpants for talk is 200 and maxNumberOfParticipants in workshop is 300; the talk max number of participants should be able to share only with talk objects and max number of participants for workshop only for workshop objects.

Upvotes: 0

Views: 153

Answers (2)

Sajith Silva
Sajith Silva

Reputation: 823

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
}

Upvotes: 0

nachokk
nachokk

Reputation: 14413

1- Name of classes should be in singular and first letter should be upper case. (Event)

public class Event {

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

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

}

Childrens

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);
}

}

Upvotes: 1

Related Questions