Java Programming Notes - Part 2: Class
Fundamentals
General Form of a Class
class ClassName {
dataType variableName;
returnType methodName(parameters) {
// body
}
}
Creating Class and Object
class Student {
String name;
int age;
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
class Test {
public static void main(String[] args) {
Student s1 = new Student();
s1.name = "Alice";
s1.age = 20;
s1.display();
}
}
Overloading Methods
class MathOps {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
Constructor
class Student {
String name;
int age;
Student(String n, int a) {
name = n;
age = a;
}
}
Constructor Overloading
class Person {
String name;
int age;
Person() {
name = "Unknown";
age = 0;
}
Person(String n, int a) {
name = n;
age = a;
}
}
Passing and Returning Objects
class Box {
int length;
Box(int l) { length = l; }
boolean compare(Box b) {
return this.length == b.length;
}
Box bigger(Box b) {
if (this.length > b.length)
return this;
else
return b;
}
}
Assigning Object References
Student s1 = new Student("John", 21);
Student s2 = s1;
s2.name = "David";
s1.display(); // Prints: David - 21
Access Control
class Student {
private int rollNo;
public String name;
public void setRoll(int r) { rollNo = r; }
public int getRoll() { return rollNo; }
}
static Keyword
class Counter {
static int count = 0;
Counter() { count++; }
}
final Keyword
final class A {}
// class B extends A {} // Error: cannot inherit final class
this Keyword
class Student {
String name;
Student(String name) {
this.name = name;
}
}
Garbage Collection and finalize()
class Test {
protected void finalize() {
System.out.println("Object destroyed");
}
public static void main(String[] args) {
Test t = new Test();
t = null;
System.gc();
}
}
Wrapper Classes
int a = 10;
Integer obj = Integer.valueOf(a); // Boxing
int b = obj.intValue(); // Unboxing