Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
CITS2210
Object-Oriented Programming
Topic 4
Java:
  Classes – Extended Example
Summary: This topic demonstrates the proper use of classes to
structure Java programs with a larger example: a solution to the
first lab.
Classes
 
Classes are the basic building block in Java programs.
– All of the code that actually “runs” is in classes.
– Generally you should use one class for each kind of object in
your program.
– You will also have one class for the main program that usually
has only static methods and instance variables.
– Sometimes you may have other classes that only have static
methods and instance variables – this sometimes helps to
organise your program.
– Generally instance variables should be private or protected
(access from the same package only), but not always.
– Methods can be public, protected or private.
– Always use the most restrictive access modifier – if you don't
need to access a method from another class, make it private (you
can always change it later.)
– Similarly, always use final for thing that won't change.
– Using more restrictive modifiers will document your intentions,
and catch your errors.
Example – My solution to lab 1
public class Location {
    private int numBikesHere = 3;
    public int numBikes() { return numBikesHere; }
    public boolean hasBikes() 
       { return numBikesHere > 0; }
    public void incrementBikes() { numBikesHere++; }
    public void decrementBikes() { numBikesHere--; }
}
public class Customer {
    private int loc;
    private int dest = 
     ((int)(Math.random() * (BikeSim.numLocs -1) + loc))
       % BikeSim.numLocs;
    public Customer(int loc) { this.loc = loc; }
    public boolean atDestination() 
        { return loc == dest; }
    public void nextLocation()
        { loc = (loc + 1) % BikeSim.numLocs; }
    public int location() { return loc; }
}
Example – lab1 main class
public class BikeSim {
  static final int numLocs = 5;
  static final int maxCustomers = 10; 
  static final int numDays = 10;
  static int numCustomers = 0;
  static Location[] locations = new Location[numLocs] ;
  static Customer[] customers = new Customer[maxCustomers] ;
  public static void main(String argv[]) {
    for(int loc=0; loc