Skip to content

Java Class

Access Modifier

1) Public (Visible Everywhere)

public class MyClass {
    public int number;
    public void display() {
        System.out.println("Visible everywhere!");
    }
}

2) Protected (Visible within the same package + subclass)

class Animal {
    protected void sound() {
        System.out.println("Some sound");
    }
}

class Dog extends Animal {
    void bark() {
        sound(); // Allowed because Dog is a subclass
    }
}
3) default - package-private
class Car {
    void drive() {
        System.out.println("Driving inside the package");
    }
}

4) Private (Visible only inside the same class)

class BankAccount {
    private double balance = 1000;
    private void deductFee() {
        balance -= 10;
    }

    public double getBalance() {
        detectFee();
        return balance;
    }
}

Modifier Same Class Same Package Subclass (diff pkg) Other Packages
public
protected
(default)
private
#### Java Methods
  • Number of parameters
  • Types of the parameters
  • Order of the parameters

===Static methods cannot be overridden===

Static methods are bound to the class, not the instance

Static methods can only access static variables and methods, while instance method can access both

ClassName.methodName(args)

Static methods stored in the permanent generation space of the heap.

Overriding

@Override
void eat() {
    System.out.println("Dog is eating");
}

Abstract Class

public abstract class Animal {
    abstract void sound();
}

public class Cat extends Animal {
    void sound() {
        System.out.println("Meow")
    }
}

Interfaces

public interface Flyable {
    void fly();
}

public class Bird implements Flyable {
    public void fly() {
        System.out.println("Flying");
    }
}

Encapsulation

public class Person {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

}

Constructors

public class Person {
    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    void sayHello() {
        System.out.println("Hello my name is " + name);
    }
}

Constructors in Inheritance

public class Animal {
    public Animal() {
        System.out.println("Animal Constructor");
    }
}

public class Dog extends Animal {
    public Dog() {
        super();
        System.out.println("Dog constructor");
    }F
}

Vargs

class Geeks {
    public static void Names(String... n) {
        for(String i : n) {
            System.out.println(i + " ");
        }
        System.out.println();
    }
    public static void main(String[] args) {
        Names("geek1", "geek2");
        Names("geek2", "geek3", "geek4");
    }
}

Final Keyword

  • Final class cannot be extended
  • Final class cannot be overriden
  • Final class cannot be reassigned