Java classes

From wikinotes

Basics

NOTE:

style guide:

  • classes should begin with an uppercase letter.
  • java file should be named after class.
  • one class per module
class Person {
     // class attributes
     int age;
     String name;

     public static void main(String[] args)
     {
          //type var      instantiate()
          Person person = new Person()
     }
}

Inheritance

NOTE:

  • java does not support multiple inheritance
  • templates are almost always better than subclassing
class Vehicle {
    public void start(){}
}

class Car extends Vehicle {        // 'extends' indicates Car is a subclass of Vehicle
    public void add_gasoline(){}
}

Interfaces

core

As an alternative to subclassing, Java allows you to define interfaces. Any class that implements this interface must provide it's attributes/methods.

Where possible, it is generally preferred to use interfaces rather than subclassing.

It is also encouraged that you program to the interface, and not the specific class. This makes it easier to add more classes later that extend the interface.

interface Duck {
    public void quack(){};
    public void fly(){};
}
class MallardDuck implements Duck {  // <-- implements
    public void quack() { System.out.println('quack'); }
    public void fly() { System.out.println('flapping wings'); }
}

class RubberDuck implements Duck {
    public void quack() { System.out.println('squeak'); }
    public void fly() {}
}

generics

It is possible for your interface to reference a type, similar to how you use an ArrayList<type>.

interface Ducks<T>                  // <-- <T> indicates iface needs a type
{
    public void quack(T duck) {};   // <-- T is reused here, references type defined by <T>
}

class RubberDucks<Duck> implements Ducks
{
    public void quack(Duck duck) { System.out.println(duck.quack()); }
}

See Also: https://www.journaldev.com/1663/java-generics-example-method-class-interface

Methods

See java methods.