javaoops
javaoops
// Non-abstract method
public void stop() {
System.out.println("Vehicle stopped");
}
}
In Java, abstraction can be achieved using either abstract classes or interfaces. The implements
keyword is used with interfaces, while the extends keyword is used with abstract classes. Let me
clarify both cases:
1. Abstract Classes and the extends Keyword
When a class is declared as abstract, it can have both abstract methods (without implementation)
and concrete methods (with implementation). To use an abstract class, another class must extend it
and provide implementations for the abstract methods.
Example of Abstract Class with extends:
// Abstract class
abstract class Animal {
// Abstract method (no implementation)
abstract void sound();
// Concrete method
public void sleep() {
System.out.println("Animal is sleeping");
}
}
@Override
public void sleep() {
System.out.println("Dog is sleeping");
}
}
// Subclass 1: Dog
class Dog extends Animal {
// Providing specific implementation for the sound() method
@Override
void sound() {
System.out.println("Dog barks");
}
}
// Subclass 2: Cat
class Cat extends Animal {
// Providing specific implementation for the sound() method
@Override
void sound() {
System.out.println("Cat meows");
}
}
@Override
public void move() {
System.out.println("Bird flies");
}
}
In object-oriented programming (OOP), inheritance allows one class to inherit the properties and
methods of another class. Java supports certain types of inheritance, but unlike other programming
languages like C++, Java does not support multiple inheritance with classes (to avoid complexity and
ambiguity). Below are the main types of inheritance:
1. Single Inheritance
In single inheritance, a class inherits from one parent (or superclass). This is the simplest form of
inheritance.
Example:
class Animal {
void eat() {
System.out.println("This animal eats food");
}
}
// Second interface
interface CanBark {
void bark();
}
interface CanBark {
void bark();
}
@Override
public void bark() {
System.out.println("The dog barks");
}
}
void meow() {
System.out.println("The cat meows");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Output: The dog eats
dog.bark(); // Output: The dog barks