Recap 04062025
Recap 04062025
Abstraction:
hide the complex implementation details and only show the essential information to user
Inheritance:
Polymorphism:
allows executing different behavior, for different types, which are determined at runtime
Encapsulation:
2 meanings:
hiding some fields and methods from public access (e.g: a class can have private
fields and they can only be accessed via getter/setter methods)
Constructor
Used to create instances of class
if coder doesn’t write any specific constructor for class, JVM will implicitly create default
constructor. Otherwise, the default constructor will not be created implicitly
The constructor can’t be used with keywords: abstract, static, final, native, synchronized
To create a new instance of class, using “new” keyword along with constructor
Demo constructor:
package objectnclass.constructor;
4/6/2025 1
public String getName() {
return name;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
'}';
}
}
package objectnclass.constructor;
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
'}';
}
}
package objectnclass.constructor;
4/6/2025 2
Result:
Destructor
In Java, there’s no concept of destructor like in C++
garbage collector: a mechanism in Java to delete objects which are no longer referenced →
prevent memory leaks
finalize() method:
any class has this method. It allows cleanup operations before the object is reclaimed
by garbage collector
package objectnclass;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* This class simulates the process of opening and closing resources (in this case: a BufferReader
*/
public class Resource implements AutoCloseable {
private BufferedReader reader;
4/6/2025 3
}
@Override
public void close() throws IOException {
if (reader != null) {
reader.close();
System.out.println("Tài nguyên đã được đóng.");
}
}
}
package objectnclass;
import java.io.IOException;
Result:
Subclass
Aka child class
4/6/2025 4
Reuse functionality and attributes of parent class
Can add new attributes/methods of parent class or redefine methods of parent class
Demo subclass:
package objectnclass.subclass;
// Parent class
class Animal {
void eat() {
System.out.println("Động vật đang ăn.");
}
}
// Subclass
class Dog extends Animal {
void bark() {
System.out.println("Chó đang sủa.");
}
}
Result:
4/6/2025 5
can only access static members of outer class
inner class:
this class can only be accessed via an instance of the outer class
local class:
can access local variables and method arguments, that are final or effectively final
anonymous class:
package objectnclass.nestedclass;
class Outer {
private static String message = "Hello from Outer";
Result:
4/6/2025 6
2. inner class:
package objectnclass.nestedclass;
class SecondOuter {
private String message = "Hello from Outer";
class Inner {
void display() {
System.out.println(message);
}
}
}
Result:
3. local class:
package objectnclass.nestedclass;
class ThirdOuter {
void method() {
class Local {
void display() {
System.out.println("Inside Local class");
}
}
Local local = new Local();
local.display();
}
}
4/6/2025 7
ThirdOuter outer = new ThirdOuter();
outer.method();
}
}
Result:
4. anonymous class:
package objectnclass.nestedclass;
interface Greeting {
void greet();
}
Result:
4/6/2025 8
Method override
Aka runtime polymorphism
The method in subclass is the same as the method in parent class in terms of signature
Return type of method in subclass is either the same as that in parent class or subclass of that
in parent class
Access modifier of method in subclass must be larger than that in parent class
Exception of method in subclass mustn’t be new or larger than that in parent class
Demo overriding:
package overloadnoverride;
class Animal {
// Method in superclass
public void sound() {
System.out.println("Animal makes a sound");
}
}
4/6/2025 9
Method overload
Often happens in a single class
Overloading rules:
same name
Demo overloadding:
package overloadnoverride;
class Calculator {
// Overloaded method to add two integers
public int add(int a, int b) {
return a + b;
}
4/6/2025 10
}
}
package mutablenimmutable;
class MutablePerson {
private String name;
private int age;
4/6/2025 11
public void setAge(int age) {
this.age = age;
}
}
Immutable Object
Its state can’t be modified after initialization
package mutablenimmutable;
final class ImmutablePerson {
private final String name;
private final int age;
4/6/2025 12
return age;
}
}
StringBuffer: mutable, thread-safe, less efficient than StringBuilder in terms of memory and
performance
package mutablenimmutable;
public class HandleStringExample {
// Concatenates to String
public static void concat1(String s1)
{
s1 = s1 + "world";
}
// Concatenates to StringBuilder
public static void concat2(StringBuilder s2)
{
s2.append("world");
}
// Concatenates to StringBuffer
public static void concat3(StringBuffer s3)
{
s3.append("world");
4/6/2025 13
}
// String 2
StringBuilder s2 = new StringBuilder("Hello");
concat2(s2);
System.out.println("StringBuilder: " + s2); // s2 is changed
// String 3
StringBuffer s3 = new StringBuffer("Hello");
concat3(s3);
System.out.println("StringBuffer: " + s3);// s3 is changed
}
}
Besides, can boxing by using valueOf or wrapper constructor (deprecated since Java 9):
Unboxing: conversion of a object of a wrap class into its corresponding primitive value
boolean Boolean
byte Byte
char Character
4/6/2025 14
float Float
int Integer
long Long
short Short
double Double
Can be used in
No Yes (e.g: List , Map , ...)
Collections?
3.9. Exception
Exception: unwanted or unexpected event that occurs during runtime and disrupts normal flows
of program
If an exception occurs and is not handled, the program terminates abruptly and the code after it
will never execute.
4/6/2025 15
Checked Exceptions: checked at compile-time → compile-time exceptions
User-defined Exceptions:
package exception;
4/6/2025 16
3.10. Interface, Abstract Class and Enum
Interface
A reference type, similar to a class but not a class
Interfaces and its methods are abstract by default → no need to declare interface with
“abstract” keyword
Java 8 introduced default and public static methods (these methods are concrete methods)
Java 9 introduced private methods, both static and non-static (these methods are concrete
methods)
Example of interface:
package abstractinterface;
interface IAnimal {
void makeSound(); // phương thức trừu tượng
}
class Cat implements IAnimal {
@Override
public void makeSound() {
System.out.println("Meow! Meow!");
}
}
class Cow implements IAnimal {
@Override
public void makeSound() {
System.out.println("Moo! Moo!");
}
}
public class InterfaceExample {
public static void main(String[] args) {
IAnimal myCat = new Cat(); // using interface as reference type
IAnimal myCow = new Cow();
myCat.makeSound();
4/6/2025 17
myCow.makeSound();
}
}
Abstract class
An incomplete class, acting like a blueprint for other classes
Can’t be instantiated directly, but can still have constructors, which will be called by its
subclasses during their construction
Can contain both abstract methods (methods with no implementation) and concrete methods
(methods with an implementation)
package abstractinterface;
@Override
public void move(String speed) {
System.out.println("Dog is moving at " + speed + " speed");
}
4/6/2025 18
@Override
public void makeNoise() {
super.makeNoise();
}
}
public class AbstractClassExample {
public static void main(String[] args) {
Dog dog = new Dog("small", 15);
dog.move("slow");
dog.makeNoise();
}
}
Why still use interface when can use abstract class instead?
A class can only extend one (abstract) class, but can implement multiple interfaces → using
interfaces will be more flexible
Enum
Special data type that contains predefined constants
An enum type is like an array, but its elements are known, not changeable. Each element can be
accessed with a constant name, instead of index
package enumdemo;
enum DayOfTheWeek {
SUN, MON, TUES, WED, THURS, FRI, SAT
}
public class EnumExample {
public static void main(String[] args) {
DayOfTheWeek weekDay = DayOfTheWeek.TUES;
System.out.println(weekDay); //TUES
4/6/2025 19
System.out.printf("Name is %s, Ordinal value = %d%n", weekDay.name(), weekDay.ordinal())
}
}
4/6/2025 20