Java - tutorial - 12/13 - various

revision:


Java - inheritance

In Java, it is possible to inherit attributes and methods from one class to another. The "inheritance concept" is grouped into two categories:

subclass (child): the class that inherits from another class.
superclass (parent): the class being inherited from.
To inherit from a class, use the extends keyword.

example

        class Vehicle {
            protected String brand = "Ford";        // Vehicle attribute
            public void honk() {                    // Vehicle method
              System.out.println("Tuut, tuut!");
            }
        }
        class Car extends Vehicle {
            private String modelName = "Mustang";    // Car attribute
            public static void main(String[] args) {
                // Create a myCar object
                Car myCar = new Car();
                // Call the honk() method (from the Vehicle class) on the myCar object
                myCar.honk();
                // Display the value of the brand attribute (from the Vehicle class) and the value 
                //of the modelName from the Car class
                System.out.println(myCar.brand + " " + myCar.modelName);
            }
        }
    

If you don't want other classes to inherit from a class, use the final keyword.


Java - polymorphism

polymorphism means "many forms", and it occurs when we have many classes that are related to each other by inheritance.

Inheritance lets us inherit attributes and methods from another class.
Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in different ways.

example

        class Animal {
            public void animalSound() {
              System.out.println("The animal makes a sound");
            }
        }
        class Pig extends Animal {
            public void animalSound() {
              System.out.println("The pig says: wee wee");
            }
        }
        class Dog extends Animal {
            public void animalSound() {
              System.out.println("The dog says: bow wow");
            }
        }
        class Main {
            public static void main(String[] args) {
              Animal myAnimal = new Animal();  // Create a Animal object
              Animal myPig = new Pig();  // Create a Pig object
              Animal myDog = new Dog();  // Create a Dog object
              myAnimal.animalSound();
              myPig.animalSound();
              myDog.animalSound();
            }
        }
    

Java - inner classes

In Java, it is also possible to nest classes (a class within a class).

the purpose of nested classes is to group classes that belong together, which makes your code more readable and maintainable.
to access the inner class, create an object of the outer class, and then create an object of the inner class.

Unlike a "regular" class, an inner class can be private or protected. If you don't want outside objects to access the inner class, declare the class as private.

example

        class OuterClass {
            int x = 10;
            private class InnerClass {
              int y = 5;
            }
        }
        public class Main {
            public static void main(String[] args) {
              OuterClass myOuter = new OuterClass();
              OuterClass.InnerClass myInner = myOuter.new InnerClass();
              System.out.println(myInner.y + myOuter.x);
            }
        }
    

An inner class can also be static, which means that you can access it without creating an object of the outer class.

a static inner class does not have access to members of the outer class.

One advantage of inner classes, is that they can access attributes and methods of the outer class.

example

        class OuterClass {
            int x = 10;
            class InnerClass {
              public int myInnerMethod() {
                return x;
              }
            }
        }
        public class Main {
            public static void main(String[] args) {
              OuterClass myOuter = new OuterClass();
              OuterClass.InnerClass myInner = myOuter.new InnerClass();
              System.out.println(myInner.myInnerMethod());
            }
        }
        // Outputs 10
    

Java - abstraction

Data abstraction is the process of hiding certain details and showing only essential information to the user.

Abstraction can be achieved with either abstract classes or interfaces.
The abstract keyword is a non-access modifier, used for classes and methods:

"Abstract class" is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).
"Abstract method" can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from).
An abstract class can have both "abstract" and "regular" methods.

example

      // Abstract class
      abstract class Animal {
        // Abstract method (does not have a body)
        public abstract void animalSound();
        // Regular method
        public void sleep() {
          System.out.println("Zzz");
        }
      }

      // Subclass (inherit from Animal)
      class Pig extends Animal {
        public void animalSound() {
          // The body of animalSound() is provided here
          System.out.println("The pig says: wee wee");
        }
      }

      class Main {
        public static void main(String[] args) {
          Pig myPig = new Pig(); // Create a Pig object
          myPig.animalSound();
          myPig.sleep();
        }
      }
    

Java - interface

An interface is a completely "abstract class" that is used to group related methods with empty bodies.

To access the interface methods, the interface must be "implemented" (kinda like inherited) by another class with the implements keyword (instead of extends). The body of the interface method is provided by the "implement" class.

Interfaces cannot be used to create objects. Interface methods do not have a body - the body is provided by the "implement" class.
Interface methods are by default "abstract" and "public".
Interface attributes are by default "public", "static" and "final".
An interface cannot contain a constructor (as it cannot be used to create objects).

Java does not support "multiple inheritance" (a class can only inherit from one superclass). However, it can be achieved with "interfaces", because the class can implement multiple interfaces.
To implement multiple interfaces, separate them with a comma.

example

      interface FirstInterface {
        public void myMethod(); // interface method
      }
      
      interface SecondInterface {
        public void myOtherMethod(); // interface method
      }
      
      class DemoClass implements FirstInterface, SecondInterface {
        public void myMethod() {
          System.out.println("Some text..");
        }
        public void myOtherMethod() {
          System.out.println("Some other text...");
        }
      }
      
      class Main {
        public static void main(String[] args) {
          DemoClass myObj = new DemoClass();
          myObj.myMethod();
          myObj.myOtherMethod();
        }
      }
    

Java - enums

An enum is a special "class" that represents a group of constants (unchangeable variables, like final variables). Enum is short for "enumerations", which means "specifically listed".

To create an enum, use the enum keyword (instead of class or interface), and separate the constants with a comma.
Note that they should be in uppercase letters.
You can access enum constants with the dot syntax.

You can also have an enum inside a class.

Enums are often used in switch statements to check for corresponding values.

An enum can, just like a class, have attributes and methods. The only difference is that enum constants are "public", "static" and "final" (unchangeable - cannot be overridden).

An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).
Enums can be used when you have values that you know aren't going to change, like month days, days, colors, deck of cards, etc.

example

      enum Level {
        LOW,
        MEDIUM,
        HIGH
      }
      
      public class Main {
        public static void main(String[] args) {
          Level myVar = Level.MEDIUM;
      
          switch(myVar) {
            case LOW:
              System.out.println("Low level");
              break;
            case MEDIUM:
               System.out.println("Medium level");
              break;
            case HIGH:
              System.out.println("High level");
              break;
          }
        }
      }
    

The enum type has a values() method, which returns an array of all enum constants. This method is useful when you want to loop through the constants of an enum.