Wednesday, 19 August 2015

Java Tutorial : Inheritance Example Vehicle

Mastering Java Inheritance: A Practical Vehicle Class Example

🌟 Want to become a Java Pro? Subscribe to Ram N Java for more simple tutorials!

What is Inheritance in Java?

Inheritance is a powerful feature in Java that allows one class (the subclass) to acquire the properties and methods of another class (the superclass). It promotes code reusability and establishes a natural hierarchy between objects.

The Vehicle and Car Relationship

In this tutorial, we use a classic example to demonstrate the "IS-A" relationship:

  • Vehicle Class (Superclass): This is the general parent class. It contains basic properties like vehicleType.
  • Car Class (Subclass): This is a specific type of vehicle. By using the extends keyword, the Car class inherits everything from the Vehicle class.

Because a Car IS-A Vehicle, it can access the members of the Vehicle class as if they were its own.

How it Works in Code

When we create an object of the Car class, we can set values for both the car's specific model and the general vehicle type inherited from the parent.

In our example, we assign "Car" to the inherited vehicleType and "Sports" to the modelType. When we call a method to display details, Java seamlessly pulls data from both classes to show the full picture.

Watch More Java Tutorials from Ram N Java

Expand your knowledge by checking out these related videos:


Click here to watch in Youtube :
https://www.youtube.com/watch?v=tSVtLPh3X8o&list=UUhwKlOVR041tngjerWxVccw

Click the below Image to Enlarge

Car.java
/*
 * Super class(Parent)
 */
class Vehicle
{
    String vehicleType;
}

/*
 * Sub class(Child)
 */
public class Car extends Vehicle
{

    String modelType;

    public void showDetail()
    {
        /*
         * accessing Vehicle class member.
         */
        vehicleType = "Car"; 
        modelType = "sports";
        System.out.println(modelType + " " + vehicleType);
    }

    public static void main(String[] args)
    {
        Car car = new Car();
        car.showDetail();
    }
}
Output
sports Car

To Download InheritanceDemoVehicleApp Project Click the below link
https://sites.google.com/site/javaee4321/java/InheritanceDemoVehicleApp.zip?attredirects=0&d=1

See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • No comments:

    Post a Comment

    Tutorials