Java Classes, Members &
Methods
Class Instantiation
• A class is a blueprint; objects are concrete instances.
• Define:
```java
class MyClass { int x = 42; }
```
• Instantiate:
```java
MyClass obj = new MyClass();
System.out.println(obj.x); // 42
```
Access Modifiers
• public – visible everywhere
• private – visible only within its own class
• (default) – package‑private, accessible inside
same package
• Encapsulation prevents misuse & protects
state.
Access Example
• ```java
class Sample {
private int alpha;
public int beta;
int gamma; // default
void setAlpha(int v){ alpha = v; }
int getAlpha(){ return alpha; }
}
Sample s = new Sample();
s.setAlpha(99);
// s.alpha = 10; // compile error
```
Method Overloading
• Same method name, different parameter list.
• Chosen at compile time based on signature.
• ```java
void demo(){}
void demo(int a){}
int demo(int a,int b){return a+b;}
```
Overloaded Constructors
• Multiple ways to create an object.
• ```java
class Box {
int w,h,d;
Box(){ w=h=d=0; }
Box(int size){ w=h=d=size; }
Box(Box b){ w=b.w; h=b.h; d=b.d; }
}
```
• Copy constructor initializes from another object.
Static Members & Methods
• Belong to the class not individual objects.
• Single shared copy.
```java
class Counter{
static int count;
Counter(){ count++; }
static int howMany(){ return count; }
}
```
• Access with `ClassName.member`.
Static Initialization Block
• Executed once when class is loaded.
• ```java
class Roots{
static double SQRT2;
static {
SQRT2 = Math.sqrt(2);
}
}
```
• Instantiate objects with constructors.
• Control visibility using access modifiers.
• Reuse names by method/constructor
overloading .
• Share utilities through static members &
methods.
• Prepare class‑wide data inside static blocks .