Java classes, objects, inheritance and polymorphism
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.Leave a Comment