First time here? Please, start at the beginning.

Monday, August 23

Part 1.3: Java Concepts Example

Yes, finally. Just source + inline comments here. You might want to copy-paste to avoid the text wrapping.
//no imports needed here

//abstract classes cannot be instantiated, only extended
abstract class Vehicle {
 //private member variables is good encapsulation, but subclasses need protected, which works just as well in this case
 protected final int fuelCapacity; // Java uses final to indicate a constant. I believe const works as well
 protected int fuelLevel;
 protected boolean running;

//Vehicle has to initalize the constant fuelCapacity
// this is also inderited by subclasses
public Vehicle(int fCap) {
 fuelCapacity = fCap;
 running = false;
}

public int getFuelCapacity() { return fuelCapacity; } // a practice of mine:
public int getFuelLevel()    { return fuelLevel;    } // making things line up
public boolean isRunning()   { return running;      }

// javadoc comment, not going into detail on that yet
/** returns true if full */
public boolean setFuelLevel(int x) {
 if(x > fuelCapacity) x = fuelCapacity; // encapsulation in action
 fuelLevel = x;
 return fuelLevel == fuelCapacity; // comparison, same an C++
}

// left up to subclasses to decide how this works
/** should return true if successful */
public abstract boolean start();

}// end of Vehicle

class Car extends Vehicle {
 public Car() {
  super(40); // calls super-class constructor
 }
 public boolean start() {
  if(running == true ) { return false; } // it's already running, so we can't start it
  running = true;
  return true;
 }
}

public class Example {
 public static void main(String[] args) {
  Car theCar = new Car();
  //Vehicle myRide = new Vehicle(); // compiler error, class is abstract
  Vehicle myRide = theCar; // works, Car is a subtype of Vehicle
  myRide.start();
  System.out.println(myRide.isRunning()); // prints true
 }
}

That should do it. Any questions, leave 'em in the comments.

I'll wait a couple days, but the next post should be the uChat source with comments similar to this. Then we'll go from there. The 3 main areas to cover are threads, network communication, and GUI creation. What sounds the most interesting?

No comments:

Post a Comment