·  JAVA – Syntax – Terms – Class

 

- Info:

  - Class defines type of Object.

  - Class is collection of properties and methods which represent certain type of data, for instance: car, animal, food.

  - Class is defined by using class keyword.

  - If class has defined method main() it can be executed which calls this method:

    javac Test.java arg0 arg1 arg2

  - Class can hold static objects of its own kind.

 

- class keyword is followed by:

  - class name

  - optional keyword extends followed by single class which it extends

  - optional keyword implements followed by list of interfaces seprated by ','

  - optional constructor

  - optional destructor

  - optional properties (variables, objects)

  - optional methods (functions)

 

- Simple:

  - This example defines simple class with defined constructor and single property and method.

  - Create JAVA Console Application Test.java

 

    Test.java

    public class Test{ 

      public static void main(String[] args) { 

        Car fiat = new Car(200);

            fiat.startEngine();           

      }

    }

    

    class Car {

      Car(int topSpeed) { this.topSpeed = topSpeed; }                                  //Constructor.

      private int  topSpeed;                                                           //Property.

      public  void startEngine() { System.out.println("Accelerating to "+topSpeed); }  //Method.

    }

 

- Complex:

  - This example defines complex class which extends class Item and implements two interfaces.

  - Class constructor calls parent constructor.

  - Java doesn't support destructors so none is implemented, instead you can explicitly call some function like close().

  - Create JAVA Console Application Test.java

 

    Test.java

    public class Test{ 

      public static void main(String[] args) {  

        Instrument instrument = new Instrument(100);

                   instrument.sound();              

        Instrument.drums.fall();

      }

    }

    

    interface SoundInterface {

      public int  i=10;

      public void sound();

    }  

    

    interface GravityInterface {

      public double g=9.81;

      public void   fall();

    }  

    

    class Item {

      int weight; 

      Item(int weight) { this.weight = weight; }

      int getWeight() { return weight; };

    }

    

    class Instrument extends Item implements SoundInterface, GravityInterface {

      Instrument(int weight) { super(weight); } ;

      static Instrument drums = new Instrument(500); //Static object of this class.

      public void sound() { System.out.println("Playing note"        ); };

      public void fall () { System.out.println("Falling from the sky"); };

    }