Post

Java) Variable Initialization / Modifiers / Polymorphism / Interfaces / Anonymous Classes

Java) Variable Initialization / Modifiers / Polymorphism / Interfaces / Anonymous Classes

This post was migrated from Tistory. You can find the original here.

Member Variable Initialization

1
2
3
4
5
6
7
8
9
class InitTest{
    int x;
    int y = x; // Member variables get a default value even without explicit initialization

    private void method1(){
        int i;
        int j = i; // Local variables cause an error if used before being initialized
    }
}
  • Default values
    • boolean: false
    • char: ‘’
    • reference types: null
  • Variable initialization order
    • Class variable (cv) initialization -> instance variable (iv) initialization
    • Automatic initialization -> explicit initialization -> initialization blocks / constructors
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Main{
    static {
        System.out.println("Class initialization block");
    }

    {
        System.out.println("Instance initialization block");
    }

    private Main(){
        System.out.println("Instance constructor");
    }

    public static void main(String[] args){
        System.out.println("Start Main");
        Main t = new Main();
        Main t2 = new Main();
    }
}

Result
Class initialization block
Start Main
Instance initialization block
Instance constructor
Instance initialization block
Instance constructor

The class initialization block runs first, only once, and the instance initialization block always runs before the constructor.

For changing member variables, stick to getter/setter methods.


Modifiers

Access modifiers

  • Class: public, (default)
  • Method / member variable / constructor: public, protected, (default), private
  • Local variable: none allowed

Other modifiers

  • final
    • class: cannot be changed, cannot be extended
    • method: cannot be overridden
    • member variable / local variable: behaves as a constant
  • abstract
    • class: indicates the class contains an abstract method
    • method: indicates the method is declared but not implemented (an abstract method)

Polymorphism, Reference Variables

  • Polymorphism: the various forms that arise from letting a parent-type reference variable point to a child instance
    • Polymorphism of parameters: parameters can be declared as the parent type so they can be handled uniformly.

Casting Reference Variables

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class Main {
    public static void main(String[] args) {
        Car car = new Car();
        FireCar firecar = new FireCar();

        Car re_firecar = (Car) firecar;
        FireCar re2_firecar = (FireCar) re_firecar;
        re2_firecar.fire();

//        FireCar re_car = (FireCar) car; // Error from here on
//        re_car.fire();
        System.out.println( car instanceof  FireCar); //false
    }
}

class Car{
    void say(){
        System.out.println("Car");
    }
}

class FireCar extends Car {
    void fire(){
        System.out.println("fire!");
    }
}

Casting a child to its parent is always fine, but casting a parent to a child must be explicit. In fact, it seems this only works if the object was originally a child cast up to the parent — child -> parent -> child.
Whether a cast is valid can be checked with instanceof.

  • toString() is a method of the Object class
  • reference variable + string = reference variable.toString() + string

Modules / Packages

Module: a container that groups multiple packages and resources together
module > package
Files like module-info.java and package-info.java seem to allow managing things with a variety of options.

interface

Regarding interfaces

  • All member variables must be public static final.
  • All methods must be public abstract.
    Both can be omitted, and the compiler adds them automatically.
  • A class can extend and implement at the same time.
1
2
3
4
5
6
7
8
9
10
class A extends B implements C{
    public void c(){
        System.out.println("c implemented by a");
    }
}

interface C{
    /** Description of c that must be implemented */ 
    void c(); // public abstract omitted
}
  • Interface-type parameter: when calling the method, it means an instance of a class that implements this interface must be supplied as the argument.
  • Interface as the return type: it means the method returns an instance of a class that implements this interface.

Polymorphism Using Interfaces

1
2
3
Fightable f = (Fightable)new Fighter();
or
Fightable f = new Fighter();

It’s possible to reference an instance of an implementing class through an interface-type reference variable.

default/static Methods

Originally neither was allowed, but
there was no reason static methods — being independent of any instance — couldn’t be added.
For default, ideally an interface never changes, but change is bound to happen eventually, and this is the countermeasure for that. (If you add an abstract method, every existing class that implements the interface would have to implement the newly added method.)

1
2
3
4
5
6
7
8
9
interface Test{
    static void saystack(){
        System.out.println("say stack");
    }

    default void say() {
        System.out.println("hello");
    }
}

Likewise, public can be omitted here too.

Conflict resolution rules

  • Conflict between default methods of multiple interfaces -> the implementing class must override it.
  • Conflict between a default method and a parent class’s method -> the parent class’s method is inherited and the default method is ignored.

Anonymous Classes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Animal {
    public String bark() {
        return "The animal cries";
    }
}

public class Main {
    public static void main(String[] args) {
        Animal dog = new Animal() {
            // @Override method
            public String bark() {
                return "The dog barks";
            }

            // Newly defined method
            public String run() {
                return "Time to run";
            }
        };

        dog.bark();
        dog.run(); // ! Error - cannot be called from outside
    }
}

Source
As shown above, you can define a class and create an object for it at the same time — it’s typically used for one-off overriding.
Note that only the overridden method can be used; a newly defined method cannot be called from outside. Even if you define a new method, it doesn’t exist on Animal, so it results in an error (a consequence of the polymorphism rule).

This post is licensed under CC BY-NC 4.0 by the author.