CONSTRUCTORS AND POLYMORPHISM
IN JAVA - ASSIGNMENT
1. What is Constructor?
A constructor is a special method in Java that is
automatically called when an object is created. It has
the same name as the class and is mainly used to
initialize variables.
class Student {
Student() {
[Link]("Constructor called");
}
}
Student s = new Student();
2. What is Constructor Overloading?
Constructor overloading means creating multiple
constructors in the same class with different
parameters. It allows objects to be initialized in
different ways.
class Student {
Student() {
[Link]("Default constructor");
}
Student(String name) {
[Link]("Name: " + name);
}
Student(String name, int age) {
[Link](name + " " + age);
}
}
3. What is Constructor Chaining?
Constructor chaining is calling one constructor from
another constructor of the same class using 'this()'. It
helps reuse code and avoids repetition.
class Student {
Student() {
this("Shalin");
[Link]("Default constructor");
}
Student(String name) {
[Link]("Name: " + name);
}
}
4. What is Polymorphism?
Polymorphism means 'many forms'. It allows one
method or object to behave differently in different
situations. It is mainly of two types: Compile-time
polymorphism (method overloading) and Runtime
polymorphism (method overriding).
Example of Method Overriding (Runtime
Polymorphism):
class Animal {
void sound() {
[Link]("Animal sound");
}
}
class Dog extends Animal {
void sound() {
[Link]("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
[Link]();
}
}
Conclusion
Constructors help initialize objects, overloading
provides flexibility, chaining avoids repetition, and
polymorphism improves reusability and flexibility of
programs. These concepts are very important in Java
OOP.