A class is a blueprint for creating objects. It defines the properties (attributes) and behaviors (methods) of objects.
Defining Classes in Java includes these components:
- Adding Instance Variables
- Adding Instance Methods
- Adding Variables
- Adding Methods
- Adding Static Methods
1.) Adding Instance Variables:
These are non-static variables defined inside a class but outside any method. Each object gets its own copy.
class Student {
String name;
int age;
}2.) Adding Instance Methods:
Instance methods operate on instance variables.
class Student {
String name;
Student(String name) {
this.name = name;
}
void display() {
System.out.println("Student Name: " + name);
}
public static void main(String[] args) {
Student s = new Student("John");
s.display(); // Output: Student Name: John
}
}3.) Adding Class Variables:
Class variables are shared among all instances. Declared with static.
class Employee {
static String company = "Tech Corp"; // Class variable
String name;
Employee(String name) {
this.name = name;
}
public static void main(String[] args) {
Employee e1 = new Employee("Alice");
Employee e2 = new Employee("Bob");
System.out.println(e1.company); // Output: Tech Corp
System.out.println(e2.company); // Output: Tech Corp
}
}4.) Adding Class Methods:
Static methods work with class variables or logic that doesn’t depend on instance state.
class Employee {
static String company = "Tech Corp";
static void changeCompany(String newCompany) {
company = newCompany;
}
public static void main(String[] args) {
Employee.changeCompany("NewTech");
System.out.println(Employee.company); // Output: NewTech
}
}5.) Adding Static Methods:
Static methods are utility methods and do not depend on object state.
class MathOperations {
static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
System.out.println(MathOperations.add(5, 3)); // Output: 8
}
}
Discussion 0