Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Java SE Core Fundamentals: Cross-Platform Toolchain, OOP, and Thread Creation

Tech 1

Java SE Cross-Platform & Toolchain

Java’s "write once, run anywhere" capability relies on the JVM (Java Virtual Machine), bundled with both JDK and JRE.

  • JDK (Java Development Kit): Comprises JRE plus development utilities like javac (compiler), java (launcher), javap (disassembler), and javadoc (documentation generator).
  • JRE (Java Runtime Environment): Contains JVM and the Java SE standard class library—sufficient for executing precompiled .class bytecode files.

Source file rules:

  • A .java file may hold multiple non-public classes but exactly one public class, whose name must match the filename exactly.
  • Each class compiles to a separate .class bytecode file.
  • Any class can define a main method as an entry point; launch it by running its corresponding .class file.

Java Object-Oriented Programming

Arrays in Java are heap-allocated objects; their reference variables live on the stack.

  • Static methods/variables load when the class initializes, while instance members exist only after object instantiation—so static methods cannot directly invoke instance methods or access instance variables.
  • If no explicit constructor is defined, the Java compiler provides a default no-argument constructor. A parameterized constructor disables the default no-arg one, which must be redefined explicitly if needed; multiple constructors are allowed via method overloading.
  • All Java classes inherit directly or indirectly from java.lang.Object, the root of the inheritance hierarchy.
  • super() invokes a parent class constructor (only usable in subclasses, must be first line) and cannot be paired with this() in the same constructor block; this() calls another constructor of the current class.

Method Overriding

Overriding lets a subclass reimplement an accessible parent method with an identical signature (return type, method name, parameter list—no changes to the "shell").

class Shape {
    void draw() {
        System.out.println("Rendering a generic shape");
    }
}

class Circle extends Shape {
    @Override
    void draw() {
        System.out.println("Drawing a circle with radius");
    }
}

class Square extends Shape {
    @Override
    void draw() {
        System.out.println("Drawing a square with side length");
    }
}

public class OverrideDemo {
    public static void main(String[] args) {
        Shape generic = new Shape();
        Circle round = new Circle();
        Shape roundShape = new Circle();

        generic.draw();   // Executes Shape's draw
        round.draw();     // Executes Circle's draw
        roundShape.draw();// Executes Circle's draw (runtime type check)
    }
}

At compile time, only the reference type is validated, so roundShape.draw() compiles because Shape has draw(). At runtime, the JVM uses the actual object type to select the method. Trying to call a subclass-only method (e.g., Circle’s calculateArea()) via a Shape reference will throw a compile error.

Polymorphism

Polymorphism enables a single method signature to exhibit different behaviors across implementations, supporting uniform handling of related objects. It requires three conditions:

  1. Inheritance between classes
  2. Method overriding by subclasses
  3. Parent class reference pointing to a subclass object

Parent references cannot invoke subclass-exclusive methods without casting.

abstract class ElectronicDevice {
    abstract void powerOn();
}

class SmartPhone extends ElectronicDevice {
    @Override
    void powerOn() {
        System.out.println("Booting smartphone with Android");
    }
    void takePhoto() {
        System.out.println("Capturing photo with 50MP camera");
    }
}

class Laptop extends ElectronicDevice {
    @Override
    void powerOn() {
        System.out.println("Booting laptop with Linux");
    }
    void runCompiler() {
        System.out.println("Compiling Java source files");
    }
}

public class PolymorphismDemo {
    public static void main(String[] args) {
        activateDevice(new SmartPhone());
        activateDevice(new Laptop());

        ElectronicDevice phoneDevice = new SmartPhone(); // Upcast
        phoneDevice.powerOn();
        SmartPhone actualPhone = (SmartPhone) phoneDevice; // Downcast
        actualPhone.takePhoto();
    }

    static void activateDevice(ElectronicDevice device) {
        device.powerOn();
        if (device instanceof SmartPhone) {
            ((SmartPhone) device).takePhoto();
        } else if (device instanceof Laptop) {
            ((Laptop) device).runCompiler();
        }
    }
}

Using activateDevice(ElectronicDevice) avoids writing separate methods for SmartPhone and Laptop, unifying type handling.

Java Multithreading

Java offers three primary thread creation approaches; implementing Runnable is preferred to bypass single-inheritance limits and enable shared object usage across threads.

  1. Create a class implementing Runnable
  2. Override run() to define thread execution logic
  3. Launch via new Thread(runnableInstance).start()
class NumberPrinter implements Runnable {
    private final int threadId;
    private final int maxCount;

    public NumberPrinter(int threadId, int maxCount) {
        this.threadId = threadId;
        this.maxCount = maxCount;
    }

    @Override
    public void run() {
        for (int i = 1; i <= maxCount; i++) {
            System.out.printf("Thread %d: Count %d%n", threadId, i);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                System.out.printf("Thread %d interrupted%n", threadId);
            }
        }
    }

    public static void main(String[] args) {
        Thread printer1 = new Thread(new NumberPrinter(1, 5));
        Thread printer2 = new Thread(new NumberPrinter(2, 5));
        printer1.start();
        printer2.start();
    }
}
Tags: Java

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.