class_object
UML Diagram
Class and Object in Java
Definition
- A class is a blueprint of an object, consisting of properties (data members) and behaviors (member functions).
- An object is a programming representation of a class and its memory is allocated in the Heap section of the memory segment.
- Java is an Object-Oriented Programming Language (OOP), meaning every element is represented as a class and object.
- Java follows four main principles of OOP:
- Encapsulation
- Inheritance
- Polymorphism
- Abstraction
Example: Student Class in Java
class Student{
// Data members or instance variables
int roll;
String name;
double marks;
// Member functions
void study(){
System.out.println(name + " is studying.");
}
void info(){
System.out.println("Roll: " + roll);
System.out.println("Name: " + name);
System.out.println("Marks: " + marks);
}
// Constructor
// 0-parameter constructor
Student(){
System.out.println("Default constructor called.");
}
// Parameterized constructor
// Student(int roll, String name, double marks){
// this.roll = roll;
// this.name = name;
// this.marks = marks;
// }
Student(int r, String n, double m){
roll = r;
name = n;
marks = m;
}
}
public class Main{
public static void main(String[] args) {
Student s1 = new Student(); // Default constructor called
s1.roll = 101;
s1.name = "John Doe";
s1.marks = 85.5;
s1.study();
s1.info();
Student s2 = new Student(102, "Jane Doe", 90.0); // Parameterized constructor called
s2.study();
s2.info();
}
}
Key Points
- Constructors:
- A default constructor initializes objects with default values.
- A parameterized constructor initializes objects with specific values.
- Member Functions:
study()andinfo()define behaviors for the Student class. - Objects Creation:
Student s1 = new Student();→ Calls the default constructor.Student s2 = new Student(102, "Jane Doe", 90.0);→ Calls the parameterized constructor.