0
0
Javaprogramming~30 mins

Parent and child classes in Java - Mini Project: Build & Apply

Choose your learning style9 modes available
Parent and Child Classes
πŸ“– Scenario: You are creating a simple program to represent vehicles. You want to show how a child class can inherit properties from a parent class.
🎯 Goal: Build a parent class called Vehicle and a child class called Car that inherits from Vehicle. Then create an object of Car and print its details.
πŸ“‹ What You'll Learn
Create a parent class named Vehicle with a String field called brand.
Create a child class named Car that extends Vehicle and adds an int field called year.
Create a constructor in Vehicle to set the brand.
Create a constructor in Car to set both brand and year.
Create a method displayInfo() in Car that prints the brand and year.
Create a Car object with brand "Toyota" and year 2020, then call displayInfo().
πŸ’‘ Why This Matters
🌍 Real World
Understanding parent and child classes helps organize code by sharing common features and adding specific details, like different types of vehicles.
πŸ’Ό Career
Inheritance is a key concept in object-oriented programming used in many software development jobs to build reusable and maintainable code.
Progress0 / 4 steps
1
Create the parent class Vehicle
Create a public class called Vehicle with a String field named brand. Add a constructor that takes a String brand parameter and sets the field.
Java
Need a hint?

Think of Vehicle as a blueprint with a brand name. The constructor sets the brand.

2
Create the child class Car
Create a public class called Car that extends Vehicle. Add an int field named year. Create a constructor that takes String brand and int year parameters. Use super(brand) to call the parent constructor and set year.
Java
Need a hint?

Use extends to inherit from Vehicle. Use super to call the parent constructor.

3
Add displayInfo method in Car
Inside the Car class, create a public method called displayInfo() that prints the brand and year in this format: "Brand: [brand], Year: [year]".
Java
Need a hint?

Use System.out.println to print the message. Access brand directly because it is inherited.

4
Create Car object and print info
In a public class called Main, create the main method. Inside it, create a Car object with brand "Toyota" and year 2020. Call the displayInfo() method on this object to print the details.
Java
Need a hint?

Remember the main method signature and how to create objects with new.