Java Classes, Objects, Inheritance & Polymorphism Guide
class Dog {
String breed;
int age;
public void bark() {
System.out.println("Bark!");
}
}
In this example, the Dog class has two properties (breed and age) and one method (bark).
Objects are instances of classes. You can create an object from a class by using the new operator. For example:
Dog myDog = new Dog();
myDog.breed = "Labrador";
myDog.age = 5;
myDog.bark();
In this example, a Dog object named myDog is created and its properties are set. The bark method is also called on the myDog object.
Inheritance is a mechanism that allows you to create a new class based on an existing class. The new class inherits all the properties and methods of the existing class and can also have its own unique properties and methods. For example:
class Labrador extends Dog {
public void fetch() {
System.out.println("Fetch!");
}
}
In this example, the Labrador class is created as a subclass of the Dog class. The Labrador class inherits all the properties and methods of the Dog class and adds its own unique method, fetch.
Polymorphism is a mechanism that allows objects of different classes to be treated as objects of a common class. Polymorphism is achieved through method overriding, which is the ability of a subclass to provide a new implementation of a method defined in its superclass. For example:
class Animal {
public void makeSound() {
System.out.println("Animal sound");
}
}
class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Meow");
}
}
Animal myAnimal = new Cat();
myAnimal.makeSound();
Cat class overrides the makeSound method of its superclass, Animal. When the makeSound method is called on a Cat object, the override version of the method is executed. This demonstrates polymorphism, as the object of the Cat class can be treated as an object of the Animal class.FAQ Section
Q1. What is the difference between a class and an object in Java?
A class is a blueprint, while an object is an instance of that class created at runtime.
Q2. What does the extends keyword do in Java?
It allows a subclass to inherit from a superclass, gaining its properties and methods.
Q3. What is method overriding in Java?
Overriding means redefining a method from the superclass in the subclass with the same signature.
Q4. How is polymorphism implemented in Java?
Polymorphism is achieved through method overriding and dynamic method dispatch at runtime.
Q5. Can a class inherit from multiple classes in Java?
No, Java does not support multiple inheritance with classes. It can be done using interfaces.
Leave a Comment