The 'final' keyword when applied to a reference variable makes it immutable, meaning it cannot be reassigned to point to another object.
The 'private' access modifier restricts access to only within the same class. It provides the highest level of encapsulation.
interface I1 {
void method1();
}
interface I2 extends I1 {
void method2();
}
class C implements I2 {
public void method1() { System.out.println("M1"); }
public void method2() { System.out.println("M2"); }
}
public class Test {
public static void main(String[] args) {
I1 obj = new C();
obj.method2();
}
}
obj is of type I1 which doesn't have method2(). Though actual object C has method2(), reference type determines what methods are accessible.
The 'instanceof' operator checks whether an object is an instance of a specific class or implements a specific interface.
class Test {
int x = 5;
{
x = 10;
}
Test() {
x = 15;
}
public static void main(String[] args) {
Test t = new Test();
System.out.println(t.x);
}
}
Instance initializer block executes after variable initialization but before constructor. Constructor executes last, setting x = 15.
'final' keyword makes a variable immutable. Once assigned, its value cannot be changed. 'const' is not a valid Java keyword.
class A {
A() {
System.out.println("A");
}
}
class B extends A {
B() {
super();
System.out.println("B");
}
}
public class Test {
public static void main(String[] args) {
new B();
}
}
super() calls parent constructor first. Parent constructor A prints 'A', then child constructor B prints 'B'.
'this' is a reference to the current object instance. It's used to refer to instance variables, call other constructors, or pass object reference.
interface A {
void show();
}
class B implements A {
public void show() {
System.out.println("B");
}
}
class C extends B {
public void show() {
System.out.println("C");
}
}
A obj = new C();
obj.show();
Polymorphism in action. obj is of type A (interface), but actual object is C. C's show() method is called, printing 'C'.
The 'final' keyword prevents a class from being extended. String, Integer, and other wrapper classes are marked final for security and immutability.