Lecture 6 Explained
Lecture 6 Explained
class. They have the same name as the class and do not have a return
type. Constructors are called automatically when an object of the class is
created. There are several types of constructors in Java:
Default Constructor: If a class does not have any constructor defined
explicitly, Java provides a default constructor automatically. This default
constructor initializes instance variables to their default values and takes no
arguments.
public class MyClass {
// Default constructor (provided by Java if not explicitly defined)
public MyClass() {
// Initialization code
}
}
// Parameterized constructor
public Student(String name, int age) {
this.name = name;
this.age = age;
}
// Copy constructor
public Student(Student other) {
this.name = other.name;
this.age = other.age;
}
// Getter methods
public String getName() {
return name;
}
public int getAge() {
return age;
}