Changes between Version 15 and Version 16 of ControlSystems/SoftwareTeam/Training/GettingStarted/IntroJava


Ignore:
Timestamp:
Oct 12, 2019, 11:03:34 PM (6 years ago)
Author:
David Albert
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • ControlSystems/SoftwareTeam/Training/GettingStarted/IntroJava

    v15 v16  
    199199When a class extends another class, it inherits all of the attributes and functions of the parent (super) class. 
    200200
    201 Create a new folder (InheritanceExample) and in it create the following java files:
     201Create a new folder (!InheritanceExample) and in it create the following java files:
    202202
    203203Fruit.java:
     
    282282  * the use of the super.eat() call to invoke the eat method of the extended super class (Fruit)
    283283
     284
     285==== Class containment
     286Sometimes it's useful to model the containment relationship between classes.  For example, consider the following classes:
     287
     288Plane.java:
     289{{{
     290import java.util.ArrayList;
     291
     292public class Plane {
     293    ArrayList<Passenger> passengers;
     294    int seats;
     295
     296    public Plane(int seats) {
     297        this.seats = seats;
     298        passengers = new ArrayList<>();
     299    }
     300
     301    public void board(Passenger p) {
     302        if (passengers.size() < seats) {
     303            passengers.add(p);
     304        } else {
     305            System.out.println("Sorry, plane is full.");
     306        }
     307    }
     308
     309    public int weight() {
     310        int w=0;
     311        for (Passenger p:passengers) {
     312             w += p.weight;
     313        }
     314        return w;
     315    }
     316}
     317}}}
     318
     319Passenger.java
     320{{{
     321public class Passenger {
     322    public int weight;
     323    String name;
     324
     325    public Passenger(String name, int weight) {
     326        this.name = name;
     327        this.weight=weight;
     328    }
     329}
     330}}}
     331
     332Containment.java
     333{{{
     334public class Containment {
     335    public static void main(String args[]) {
     336        Plane puddleHopper = new Plane(10);
     337        Passenger p1 = new Passenger("Bob", 180);
     338        Passenger p2 = new Passenger("Alice", 135);
     339
     340        puddleHopper.board(p1);
     341        puddleHopper.board(p2);
     342
     343        System.out.println("Passengers weigh "+puddleHopper.weight()+" lbs");
     344    }
     345}
     346}}}
     347
    284348== Princeton Java
    285349There's a lot to programming and you'll get to the fun stuff a lot faster if you do some self-study.  There are many Java tutorials, but if you'd like to try learning the Princeton way, try [https://introcs.cs.princeton.edu/java/home/ this one].