Wednesday, 28 August 2024

What is Abstract class and Method in Java?

In Java, an abstract class and an abstract method are key concepts in object-oriented programming, used to define classes and methods that are meant to be extended or overridden in subclasses. Here's a breakdown:



Abstract Class

  • Definition: An abstract class in Java is a class that cannot be instantiated directly. It is used as a base class for other classes to inherit from. Abstract classes are defined using the abstract
  • Purpose: Abstract classes are designed to be inherited by subclasses that provide specific implementations for its abstract methods. They can contain both abstract methods (methods without a body) and concrete methods (methods with a body).
  • Usage: Abstract classes are often used when there are some shared features among different classes, but the implementation of certain methods should be left to the subclasses.

JavaCopy codeabstract class Animal {    abstract void sound(); // Abstract method     void breathe() { // Concrete method        System.out.println("This animal breathes air.");    }}

Abstract Method

  • Definition: An abstract method is a method that is declared without an implementation (no method body) in an abstract class. It is meant to be overridden by subclasses that inherit the abstract class.
  • Purpose: Abstract methods define a method signature that must be implemented by any concrete subclass, enforcing a certain contract or behavior.
  • Usage: When a subclass extends an abstract class, it must provide an implementation for all abstract methods of the parent class, unless the subclass is also declared abstract.

javaCopy codeclass Dog extends Animal {    void sound() { // Implementing the abstract method        System.out.println("Woof");    }}

Example

Here's how an abstract class and method might be used:

javaCopy codeabstract class Vehicle {    abstract void start(); // Abstract method     void stop() { // Concrete method        System.out.println("Vehicle stopped.");    }} class Car extends Vehicle {    @Override    void start() { // Implementing the abstract method        System.out.println("Car started with key.");    }} class Bike extends Vehicle {    @Override    void start() { // Implementing the abstract method        System.out.println("Bike started with button.");    }}

In this example:

  • Vehicle is an abstract class with an abstract method start().
  • Car and Bike are concrete subclasses that provide their own implementations of the start() method.

TCCI Computer classes provide the best training in all computer courses online and offline through different learning methods/media located in Bopal Ahmedabad and ISCON Ambli Road in Ahmedabad.

For More Information:

Call us @ +91 98256 18292

Visit us @ http://tccicomputercoaching.com/

No comments:

Post a Comment