this keyword, static members, and Access Modifiers.1. Class and Object
A class defines a blueprint for objects. An object is a real instance created from that blueprint.
public class Dog {
String breed;
public void bark() {
System.out.println("Woof!");
}
public static void main(String[] args) {
Dog myDog = new Dog(); // Creating an object
myDog.bark(); // Calling method
}
} 2. Constructors
A constructor initializes an object when it is created. It has the same name as the class and has no return type.
public class MyClass {
int value;
// Constructor
public MyClass() {
value = 10;
}
public static void main(String[] args) {
MyClass obj = new MyClass();
System.out.println("Value: " + obj.value);
}
} 3. The this Keyword
The this keyword refers to the current object. It is commonly used when parameter names shadow instance variables.
public class Student {
String name;
public Student(String name) {
this.name = name; // Refers to instance variable
}
public static void main(String[] args) {
Student s = new Student("Rahul");
System.out.println("Student Name: " + s.name);
}
} 4. The static Keyword
A static method or variable belongs to the class, not to individual objects. It can be accessed without creating an instance.
public class Counter {
static int count = 0;
public Counter() {
count++; // Shared across all objects
}
public static void main(String[] args) {
new Counter();
new Counter();
new Counter();
System.out.println("Total objects created: " + Counter.count);
}
} 5. Access Modifiers
Access modifiers define how a class or its members can be accessed.
| Modifier | Accessible Within Class | Same Package | Subclass | Other Packages |
|---|---|---|---|---|
| public | Yes | Yes | Yes | Yes |
| protected | Yes | Yes | Yes | No |
| default (no modifier) | Yes | Yes | No | No |
| private | Yes | No | No | No |
Example
public class Employee {
public String name = "John"; // Accessible anywhere
private double salary = 50000; // Only this class
protected String department = "IT";
public double getSalary() { // controlled access
return salary;
}
public static void main(String[] args) {
Employee e = new Employee();
System.out.println(e.name);
System.out.println(e.getSalary());
System.out.println(e.department);
}
}