Object-Oriented Programming


Collapse Content

The Code for Classes

All code in Java is written within Classes. Classes are the template used for creating objects, or instances of a Class. The objects can then interact with each other and other input and produce output.

Classes, methods and blocks in Java are marked with curly-braces { }, which also marks the scope of variables declared within them.

//class declaration     
 class Car {    

    /*
     *  instance variables
     *  declared outside a method, so available to whole instance
     *  marked private so they cannot be accessed from outside the instance
     */             
    private String color;
    private int[] passengerWeights;         

    int speed;// not marked private, so will be accessible outside instance 

    //constructor method. this method is called when a new object is created
    public Car(String color) {
        speed = 0;
        this.color = color;  //`this` refers to the instance itself
    }

    /*
     * To keep the code encapsulated, instance variables should be marked private 
     * and accessed and changed through methods
     */     
 //access returnType methodName()
    public int getSpeed() {
        return speed;   //returns the instance variable `speed` 
    }

    public String getColor() {
        return color;
    }

    //access returnType methodName(parameters)
    // marked `void` since returns nothing
    public void accelerate(int amount) {
        if(speed+amount < 100)
            speed += amount;

    }       
    // the above methods are marked `public` so they can be called from outside the object.
    // mark a method `private` if it is just for internal use.


    // this method takes in an array as a parameter
    public void loadCar(int[] allPassengerWeights) {
        passengerWeights = allPassengerWeights;
    }

    // calculate total weight of passengers
    public int totalPassengerWeight() {
        int sum = 0; // `sum` is local variable, accessible within method
        for(int weight: passengerWeights){  // `weight` is accessible within for-loop
            sum += weight;
        }
        return sum;         
    }


    //static method - cannot access instance variables
    public static double estimatedTimeArrival(double steadySpeed, double miles) {
        return miles / steadySpeed;
    }

}

Creating and Using Objects

The above code declares a class, and to use it, we need to declare instances of it. (See The Code for Creating and Using Objects).

public class Main {

  // the `main` method uses a special syntax, and is where the program starts
  public static void main(String[] args) {
    // Declare, create and assign new Car instance      
    Car car1 = new Car("green");

    // invoke car1's public methods
    System.out.println(car1.getColor() );  //prints "green"
    car1.accelerate(10); // speed = 10

    // since Car's speed isn't private, can access it directly
    car1.speed = 170; // often you don't want to allow this
    System.out.println( car1.speed ); // prints 170

    // call Car's static method
    double hours = Car.estimatedTimeArrival(10, 30);

    System.out.println("We'll arrive in " + hours + " hours.");
    // prints "We'll arrive in 3.0 hours."      
  }

}

static and main methods

A static method (or "class method") cannot deal with the Object's instance variables, it can only deal with the parameters that it is passed (and with static variables). A static method is declared with the keyword static:

public static int average(int a, int b){
    return (a+b) / 2;
}

If this average method was in a class called Numbers, we could call it inside that class as usual:

int average = average(4, 8);

And outside the Class, with the Class name:

int avg = Numbers.average(4, 8); 

main method

All Java programs start executing from the main method. Somewhere in the code, there needs to be a method with the following header, the syntax for the main method:

 public static void main(String[] args){
   //code to start things up!
 }

View the larger code sample above to see a static and main method in action, or read more about them here.

Java Library

The Java programming language comes with a very large set of classes known as the Java Class Library. These classes provide a wide range of functionality for doing many common programming tasks. The Java Library is organized into sub-libraries known as packages, which each contain many classes.

Import
To use a Java library class, you need to import it:

//import packageName.className 
import java.util.ArrayList;  //import ArrayList so you can use it

You can also get access to all of a package's classes without specifying each Class separately. To do this, you just use an * to represent any Class. For example,

import java.util.*;

will let you use any Class in java.util, such as ArrayList and Scanner.

See The Java Library ($) for a beginner guide to using the Java Library. See the Java API Reference for a tutorial/reference to some common library classes.

Inheritance

Inheritance lets classes inherit properties from other classes, which helps with code re-use and maintenance.

// use `extends` keyword to make a class a subclass of another class.
public class Racecar extends Car {  

    // `super` refers to the parent or superclass

    public Racecar(String color){
        super(color); // `super` calls the the superclass's constructor.
    }

    // overriding a method: 
    public void accelerate(int amount) {
        if(speed + amount < 200){ // new maximum speed of 200
            speed += amount;            
        }
    }   

}

Racecar can be treated like a regular Car, except where it overrides it. This code was added to the main method above:

// Racecar is a sublcass of Car
Racecar racecar = new Racecar("blue");
racecar.accelerate(150);
System.out.println(racecar.getSpeed() );  // prints 150

Subclasses Working Together
You can use many subclasses of the same superclass together. Here's a Car agrage that can hold both Cars and Racecars:

Car[] garage = new Car[3];
garage[0] = car1;
garage[1] = racecar;        

All Classes are subclasses of Object
All Classes in Java are really extensions of the Object class. This means that they all come with certain built-in methods such as toString(). In fact, when an Object is printed, Java automatically calls that Object's toString() method.

Method Polymorphism
When toString() is called on different Classes, the specific toString() method is executed as implemented in that Class. If that Class does not have a toString() method, the code will look at its superclasses until it finds the toString() method. This means you call the same method name on a list of Objects and different method implementations will run on different objects.

Contact Us
Sign in or email us at [email protected]