Java-All Practicals 1-11
Java-All Practicals 1-11
Theory:
Java is a popular, high-level, object-oriented programming language developed by Sun Microsystems (now owned by
Oracle). It is widely used for building platform-independent applications. The Java Development Kit (JDK) is a
software development environment used for developing Java applications. It includes tools for compiling,
debugging, and running Java programs.
- Select the version you wish to download. It's often recommended to use the latest stable version.
- Choose the installer suitable for your operating system (Windows, macOS, or Linux).
- `%JAVA_HOME%\bin`.
java -version
- Save the file as `Helloworld.java`. Ensure that the filename matches the class name exactly (case-sensitive).
javac Helloworld.java
- This will create a file named `Helloworld.class`, which contains the bytecode.
Program:
class Helloworld {
System.out.println("Hello World!");
}
//Name: Dipak || Tushar
output:-
4. Conclusion
You have successfully installed the JDK, written a simple Java program, compiled it, and executed it. This "Hello World"
program serves as a basic introduction to Java programming and showcases the fundamental steps involved in
creating and running a Java application.
5. Troubleshooting Tips
- Check the Case Sensitivity: Ensure the file name and class name match exactly, including case.
- Path Issues: If you receive errors about Java not being found, double-check that the `JAVA_HOME` variable and
`Path` settings are correctly configured.
- Permissions: Ensure you have permission to execute commands in the terminal or command prompt.
Experiment 2
Aim: WAP to demonstrate Control Statements and Iteration Statements
Theory:
Control Statements
Control statements determine the flow of control in a program. They dictate how a program behaves based on certain
conditions. There are several types of control statements in Java:
1. Conditional Statements
Conditional statements allow a program to execute certain sections of code based on whether a condition evaluates
to true or false. The main types include:
if (condition) {
- if-else Statement: Executes one block of code if the condition is true and another block if it is false.
if (condition) {
} else {
if (condition1) {
} else if (condition2) {
} else {
// code if both conditions are false
- switch Statement: Allows a variable to be tested for equality against a list of values (cases).
switch (variable) {
case value1:
break;
case value2:
break;
default:
2. Jump Statements
Jump statements allow you to move the control flow to a different part of the program. Common jump
statements include:
- continue: Skips the current iteration of a loop and continues with the next iteration.
- return: Exits from the current method and optionally returns a value.
Iteration Statements
Iteration statements, also known as loops, allow a block of code to be executed repeatedly as long as a specified
condition is true. The main types of iteration statements in Java include:
1. for Loop: The `for` loop is used when the number of iterations is known beforehand. It consists of three parts:
initialization, condition, and increment/decrement.
// code to be executed }
Example
System.out.println(i); }
2. while Loop: The `while` loop continues to execute as long as a specified condition is true. It is generally used when
the number of iterations is not known beforehand.
while (condition) {
// code to be executed
Example:
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
3. do-while Loop: The `do-while` loop is similar to the `while` loop, but it guarantees that the block of code is
executed at least once, even if the condition is false initially.
do {
// code to be executed
} while (condition);
Example:
int i = 0;
do {
System.out.println(i);
i++;
Program Code:
TusharShinde”);
int x = 10;
if (x > 5) {
System.out.println("x is greater than 5");
} else {
int y = 20;
if (y > 10) {
if (y > 15) {
} else {
} else {
// Switch statement
switch (grade) {
case 'A':
System.out.println("Excellent");
break;
case 'B':
System.out.println("Good");
break;
case 'C':
System.out.println("Fair");
break;
default:
System.out.println("Invalid grade");
}
// For loop
// While loop
int j = 0;
while (j < 5) {
j++;
// Do-while loop
int k = 0;
do {
k++;
if (i == 5) {
if (i == 5) {
Output:-
Conclusion: Control Statements: Allow conditional execution of code blocks, enabling decision-making within the
program.Iteration Statements: Enable repeated execution of code blocks, facilitating tasks such as looping
through collections, performing calculations, or processing user input.Understanding these concepts is crucial
for developing efficient algorithms and controlling the logic in Java programs. They form the backbone of flow
control, making it possible to build complex applications with branching and looping behaviors.
Experiment 3
Aim: Implement a java program to calculate gross salary & net salary using the following data. Input: empno,
empname, basic salary.
Theory
1. Understanding Salaries
- Dearness Allowance (DA): A cost of living adjustment paid to employees to counteract inflation (often a percentage
of the basic salary).
- House Rent Allowance (HRA): A portion of the salary paid to employees to cover housing costs (again typically a
percentage of the basic salary).
- City Compensatory Allowance (CCA): A fixed allowance to compensate for higher costs in urban areas.
- Provident Fund (PF): A mandatory savings scheme where a portion of the salary is deducted for retirement savings.
2. Salary Calculation
Steps:
1. Imports:
- The program imports `java.util` for using the `Scanner` class to read user input.
2. Scanner Setup:
- A `Scanner` object is created to read input from the console. The locale is set to `US` to ensure that the decimal
separator is recognized correctly.
3. Input Collection:
- The program collects the employee number, name, and basic salary from the user.
4. Salary Calculations:
- It calculates DA, HRA, CCA, PF, and PT based on predefined formulas and constants.
- It computes the gross salary and then the net salary.
Program Code:
import java.util.*;
double DA = 0.70*basic;
double PF = 0.10*basic;
double PT = 100;
scan.close();
output:-
Conclusion: By utilizing control statements for input and mathematical calculations for salary components, this
program encapsulates the fundamental concepts of Java programming. This not only enhances understanding
of how salary calculations work in practice but also illustrates how to handle user input and perform calculations
programmatically.
Experiment 4
Aim: Write a Menu driven program in java to implement simple banking application. Application should read the
customer’s name, account number, initial balance, rate of interest, contact number and address field etc.
Application should have following methods. 1. createAccount() 2. deposit() 3. withdraw () 4.
computeInterest() 5. displayBalance()
Prerequisite:-
The menu-driven approach is a user interface design pattern commonly used in console applications to guide users
through various functionalities. In this lab work, we focus on implementing a simple banking application using
Java, utilizing a menu-driven system to provide a structured and interactive way for users to access different
banking operations. This method is particularly effective in ensuring ease of use and clarity, especially in
applications where multiple functionalities are available.
A menu-driven system displays a list of options or commands to the user, each associated with a specific action or
function. The user navigates through the options by selecting an appropriate command, typically by entering a
number corresponding to the desired option. This design pattern helps users understand and interact with the
program's capabilities without needing to remember specific commands or syntax.
In the context of our banking application, the menu-driven system serves as the primary interface through which
users interact with the program. The main menu presents several options, including:
1. Create Account
2. Deposit Funds
3. Withdraw Funds
4. Check Balance
5. Exit
Each of these options corresponds to a particular operation within the banking application. The user selects an option
by entering the corresponding number, which then triggers the execution of the relevant code block.
Implementation Details
1. Creating the Menu Interface: The menu interface is typically implemented using a loop, such as a while loop, which
repeatedly displays the menu until the user chooses to exit the program. Inside the loop, a switch-case
statement or a series of if-else conditions are used to execute the appropriate actions based on the user's input.
2. Handling User Input: User input is managed using the Scanner class in Java, which reads the user's selection from
the console. This input determines the path the program takes, directing it to the appropriate section of the
code to handle the requested operation. For example, if the user chooses to create an account, the program
prompts for additional details such as the account number, the account holder's name, and the initial deposit
amount.
3. Performing Banking Operations: Create Account: When this option is selected, the program collects the necessary
details from the user to set up a new account. The information is then used to create a new instance of the Bank
Account class, which is stored in a collection, such as an ArrayList, for easy management and retrieval.
4. Deposit Funds: To deposit funds into an account, the program first asks for the account number. It then verifies
the existence of the account and prompts for the deposit amount. After validating the amount, the program
updates the account balance accordingly.
5. Withdraw Funds: Like depositing, withdrawing funds requires the user to enter the account number and the desired
withdrawal amount. The program checks that the account exists and that the withdrawal amount does not
exceed the current balance before proceeding with the transaction.
6. Check Balance: This option allows the user to view the current balance of a specific account. The program asks for
the account number and retrieves the balance for display.
7. Exiting the Program: The exit option terminates the loop and subsequently ends the program. This provides a clean
and controlled exit from the application, ensuring that any necessary cleanup or final operations can be
performed before the program shuts down.
◼ User-Friendly: It provides a simple and intuitive way for users to navigate the application. Users do not need to
remember specific commands or syntax, as the options are clearly listed.
◼ Structured Navigation: It organizes the program's functionality into discrete, accessible options, making it easy
for users to find and use the features they need.
◼ Error Reduction: By guiding users through a set of predefined options, the menu-driven approach minimizes the
chances of user error, such as entering invalid commands.
◼ Ease of Expansion: The menu system can be easily expanded to include new functionalities by adding new options
to the menu and implementing the corresponding operations.
Program:
import java.util.Scanner;
class BankAccount {
customerName = sc.nextLine();
accountNumber = sc.nextLine();
balance = sc.nextDouble();
rateOfInterest = sc.nextDouble();
sc.nextLine();
contactNumber = sc.nextLine();
if(amount > 0) {
balance += amount;
}else{
balance -= amount;
}else{
}
public void computeInterest() {
balance += interest;
System.out.println("Address: "+address);
int choice;
while(true) {
System.out.println("1.Create Account");
System.out.println("2.Deposit");
System.out.println("3.Withdraw");
System.out.println("4.Compute Interest");
System.out.println("5.Display Balance");
System.out.println("6.Exit");
choice = sc.nextInt();
switch(choice) {
case 1:
account.createAccount();
break;
case 2:
account.deposit();
break;
case 3:
account.withdraw();
break;
case 4:
account.computeInterest();
break;
case 5:
account.displayBalance();
break;
case 6:
break;
default:
}
}
output:-
Conclusion: - This lab work on creating a menu-driven bank application illustrates fundamental OOP concepts
subclasses, objects, encapsulation, and collections. By implementing a structured user interface and handling
basic banking operations, students can gain hands-on experience in developing user-friendly and maintainable
software.
Experiment 5
Aim: Create a Java based application to perform various ways of Method overloading and constructor
overloading
Prerequisites:
Theory:
Method Overloading
Method overloading is a feature in Java that allows a class to have multiple methods with the same name but
different parameter lists. This means that the methods must differ in the number of parameters, the type of
parameters, or both. Method overloading is a key aspect of polymorphism in object-oriented programming, where
a single method name can be associated with multiple behaviors depending on the context in which it is called.
One of the primary benefits of method overloading is improved code readability and usability. By using the same
method name for similar actions that operate on different types of input, developers can create a more intuitive
interface. For example, if you have a method that calculates the area, you might overload it to handle both square
and rectangular shapes without needing different method names. This can make it easier for other developers to
understand how to use your class without having to remember multiple method names.
Another advantage of method overloading is that it can reduce the complexity of code. Instead of having to create
unique method names for every variation of a task, overloaded methods can simplify the interface and allow for
more straightforward method calls. This is particularly useful in situations where similar operations need to be
performed on different data types.
In summary, both method overloading and constructor overloading are essential features of Java that enhance the
language's flexibility and usability. They contribute to cleaner code, better organization, and increased readability,
making it easier for developers to work with and maintain Java applications. These concepts exemplify the
principles of polymorphism and encapsulation, which are fundamental to object-oriented programming.
Program:
CONSTRUCTOR OVERLOADING:
class Calculator {
private int a;
private int b;
// Default constructor
public Calculator() {
this.a = 0;
this.b = 0;
public Calculator(int a) {
this.a = a;
this.b = 0;
this.a = a;
this.b = b;
return a + b;
return a + b;
return a + b + c;
}
}
//name: Dipak&Tushar
Output:-
Method overloading:
class Display {
display.show(5);
display.show(3.14);
display.show("Hello, World!");
display.show(10, 20);
}
}
//name:Dipak&Tushar
output:
Conclusion: Thus, we studied to perform various ways of Method overloading and constructor overloading.
Experiment 6
Aim - To create a class 'Student’ and print the name, age and address of using an array of objects 10 students
An array is a core data structure in Java that allows you to store multiple elements of the same type in a single,
contiguous block of memory. Arrays are widely used in programming because they provide an efficient way to
store and access sequences of data. Each element in an array is stored at a specific index, allowing for fast
retrieval and modification. Arrays are particularly useful when you need to manage a collection of items, such as a
list of numbers, strings, or objects, where Each item is of the same data type.
Array Declaration and Initialization: In Java, arrays are objects that must be declared and initialized before They
can be used. The declaration of an array involves specifying the type of elements it will store and the syntax for
creating an array. The Initiative of an array involves allocating memory for the elements and optionally assigning
values to them
Declaration:
An array must be declared with a specific type, indicating the kind of elements it will hold.
Initialization:
After declaring an array, you must initialize it by allocating memory for its elements. This is done using the new
keyword, followed by the data type and the size of the array.
Accessing and Modifying: Each element in an array is accessed using its index, which starts from 0 and goes up to
1, where length is the number of elements in the array.
Arrays of Objects: In Java, you can create arrays to store objects of a particular class. When you declare an array
of objects, each element in the array holds a reference to an object, not the object itself. This means that the
array stores memory addresses pointing to the actual objects. Accessing and modifying objects in an array is like
working with primitive data types
Arrays are often used in combination with loops to process multiple elements. Java provides two main types of
loops for iterating over arrays: the traditional for loop and the enhanced for-each loop.
The traditional for loop allows you to iterate over the array using an index, providing full control over the iteration
process. This loop is useful when you need to know the index of the current element or when you need to modify
elements during iteration.
Enhanced for-each Loop: The enhanced for-each loop simplifies iteration by automatically handling the loop
counter and directly accessing each element. This loop is particularly convenient for reading elements when you
don't need to modify them or access their indices.
Advantages and Disadvantages of Arrays
Arrays are simple and efficient data structures but have limitations. They provide constant-time access to
elements and are efficient in terms of memory. However, their size is fixed once they are created, meaning you
cannot resize them without creating a new array. Additionally, arrays are homogeneous, meaning all elements
must be of the same type.
Program:
class Student {
String name;
int age;
String course;
// Default constructor
public Student() {
this.name = name;
this.age = age;
this.course = course;
System.out.println("Name: " + name + ", Age: " + age + ", Course: " + course);
}
public static void main(String[] args) {
student1.displayInfo();
Student student2 = new Student("Dipak&Tushar", 20); // Calls the constructor with 2 parameters
student2.displayInfo();
Student student3 = new Student("sakshi", 22, "IT"); // Calls the constructor with 3 parameters
student3.displayInfo();
//name:Dipak&Tushar
Output:
Conclusion
By completing this experiment, we learned how to define a class in Java, create an array of objects, and iterate
over that array to print the details of each object. This exercise reinforces key object-oriented programming
concepts, particularly working with arrays of objects, which is a common scenario in software development.
Experiment 7
Aim: To Demonstrate Constructor Chaining.
Prerequisite:
1. Constructors: These are special methods used to initialize objects. They are called when an object
is created, ensuring it is properly set up.
2. Constructor Overloading: This occurs when a class has more than one constructor with different
parameter lists, providing flexibility in how objects are initialized.
Theory:
1. What is a Constructor? A constructor is a block of code that initializes an object when it is created.
It sets up initial values for object attributes and prepares resources that the object might need
during its lifecycle. Constructors share the same name as their class and cannot return any type.
Constructors are essential for assigning values to the fields of an object and ensuring it is ready to
be used.
2. Constructor Chaining: Constructor chaining occurs when one constructor calls another constructor
to avoid duplicating code. This practice ensures that common initialization code is centralized,
promoting efficiency and reducing redundancy.
3. Types of Constructor Chaining:
1. Within the Same Class: When constructors within the same class call each other, this is done
using the this() keyword. For instance, you might have a constructor that takes no arguments
call another constructor that requires arguments, ensuring all fields are properly initialized.
This helps when you have multiple constructors with different parameters but want to
ensure that some initialization code is always executed.
2. Between Parent and Child Classes: When constructor chaining happens between a parent
and child class, it is done using the super() keyword. This is critical for object-oriented
programming, where a child class might rely on the parent class's constructor to set up
inherited fields. The super() call ensures that parent class attributes are initialized before the
child class adds its own logic.
4. Key Points:
o Order of Calls:
▪ In the case of constructor chaining within the same class, the this() call must be the first line in
the constructor to ensure proper execution flow.
▪ For chaining between parent and child classes, super() must be the first line in the constructor to
ensure that the parent class's attributes are initialized before any child-specific logic is executed.
o Purpose: Constructor chaining centralizes common initialization logic, which minimizes code
duplication. This not only improves maintainability but also reduces the chance of errors in
object creation.
o Access Control: The visibility of constructors affects constructor chaining. For example, a
child class cannot call a private constructor in the parent class using super(). Access must be
public or protected.
5. Characteristics of a Constructor:
o Same Name as the Class: This rule ensures that constructors are easily identifiable as special
methods for object initialization.
o No Return Type: Constructors cannot return any values. They are only meant to initialize
objects, and returning values would conflict with that purpose.
o Initialization Code: Constructors are typically used to set up initial values for object fields,
open connections, or perform other setup activities that are essential before the object can
be used.
Program:
class Animal {
String name;
Animal() {
Animal(String name) {
this.name = name;
int age;
Dog() {
this.age = age;
}
class Bulldog extends Dog {
String breed;
Bulldog() {
super(name, age); // calls the constructor of Dog with name and age
this.breed = breed;
OUTPUT:-
Conclusion:
Constructor chaining and overloading offer a powerful way to manage object initialization efficiently. Constructor
chaining allows multiple constructors to share common setup logic, which reduces redundancy and errors. This is
especially useful in classes with complex initializations or when dealing with inheritance in object-oriented design.
Experiment 8
Aim: Write a Java program to add n strings in a vector array.
Prerequisite: JDK 17
Theory: Vector is part of the Java Collections Framework and is similar to an array, but with two key
Before you start to use vectors, import it from the java.util.package as follow:
import java.util.Vector ;
Creating a Vector:
For example:
import java.util.Vector;
About Vectors:
• A vector in java is a dynamic data structure that can be accessed using an integer index.
• Though similar to ArrayList, it is synchronized, containing some legacy methods not available in the
collection framework.
• Iterators of vector class fail fast and throw the ConcurrentModificationException in case of concurrent
modification.
Constructors:
This creates a vector in java with an initial capacity as specified, and the increment is
also specified. With increment, the number of elements allocated each time the vector is resized
upward is specified.
Syntax:
2. Vector(int initialCapacity):
Syntax:
3. Vector():
Syntax:
4. Vector(Collection c):
Syntax:
Methods:
1. Add Elements
Boolean add(Object o)- An element is appended at the end of the vector Void add( int index V element)- The
given element is added to the specified index in the vector
2. Remove Elements
Boolean Remove (object o) – used to remove the element at the specified index in the vector. When the element
is removed, all the elements are shifted left to fill the spaces; the indices are
then updated.
3. Change Elements
The set () method can be used to change the element after adding the elements. The elements
index can be referenced as a vector is indexed. This method takes the index and the updated
element.
There are several ways to loop through a vector. One of them is the get() method.
The dynamic size of vectors avoids memory wastage, and the size of our data structure can be
Both vectors and Array Lists are dynamic. However, vectors are more advantageous as:
Program Code:
import java.util.Scanner;
import java.util.Vector;
int n = scanner.nextInt();
stringVector.add(scanner.nextLine());
while (true) {
if (newString.equalsIgnoreCase("exit")) {
break;
System.out.println(str);
Output:
Conclusion: In this experiment we studied that, a vector in java is a dynamic array with no size
limit that is part of the Java Collection Framework. We also studied the various constructors and
Theory:
Inheritance Basics: Java supports inheritance by allowing one class to incorporate another class into its
declaration. This is done by using the extended keyword. Thus, the subclass adds to (extends) the superclass.
When a class inherits from another class, the child class automatically inherits all the characteristics (member
variables) and behavior (methods) from the parent class. Inheritance is always additive; there is no way to inherit
from a class and get less than what the parent class has. Inheritance in Java is handled through the keyword
extends. When one class inherits from Another class, the child’s class extends the parent class.
For example,
The items that men and dogs have in common could be said to be common to all mammals: therefore, you
can create a MammalClass to handle these similarities.
Access modifiers:
It’s important to understand when members (both variables and methods) in the class are accessible.
• Code Reusability: The code written in the Superclass is common to all subclasses. Child classes can
directly use the parent class code.
• Method Overriding: Method Overriding is achievable only through Inheritance. It is one of the ways by
which Java achieves Run Time Polymorphism.
• Abstraction: The concept of abstract where we do not have to provide all details, is achieved through
inheritance. Abstraction only shows the functionality to the user.
• Class: Class is a set of objects which shares common characteristics/ behavior and common properties/
attributes. Class is not a real-world entity. It is just a template or Blueprints or prototype from which
objects are created.
• Super Class/Parent Class: The class whose features are inherited is known as a superclass(or a base class
or a parent class).
• Sub Class/Child Class: The class that inherits the other class is known as a subclass(or a derived class,
extended class, or child class). The subclass can add its own fields and methods in addition to the
superclass fields and methods.
• Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class
and there is already a class that includes some of the code that we want, we can derive our new class
from the existing class. By doing this, we are reusing the fields and methods of the existing class.
Types of Inheritance:
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance
Program:
Output:
Conclusion:
Thus, we have studied the concept of inheritance, types of inheritance and access specifiers.
Experiment 10
Aim: An employee works in a particular department of an organization. Every employee has an employee
number, name and draws a particular salary. Every department has a name and a head of department. The head
of department is an employee. Every year a new head of department takes over. Also, every year an employee is
given an annual salary enhancement. Identify and design the classes for the above description with suitable
instance variables and methods. The classes should be such that they implement information hiding. You must
give logic in support of your design. Also create two objects for each class.
Prerequisite:
1. Classes and Objects: Creating and using classes and objects to represent real-world entities.
2. Encapsulation: The concept of information hiding where data is kept private within a class,
accessible only through methods.
3. Inheritance: How one class can inherit properties and methods from another class.
5. Methods: Defining functions within classes that perform actions on instance variables.
Theory:
The problem revolves around modeling an organization where employees work in departments, with each
department having a head. The classes need to represent both employees and departments with proper
information hiding, meaning the sensitive attributes (e.g., salary) should only be accessible through public
methods.
• Encapsulation is important here. Data like salary, employee name, and employee number should
be made private, and public methods should be used to access or modify these fields.
• Class Design:
1. Employee Class:
2. Department Class:
Each department can have a head of department that changes every year. The annual salary enhancement can be
implemented as a method in the Employee class.
Program:
// Constructor
this.employeeNumber = employeeNumber;
this.name = name;
this.salary = salary;
// Getter methods
return employeeNumber;
return name;
return salary;
// Setter methods
this.name = name;
this.salary = salary;
}
// Method to apply salary enhancement
if (percentage > 0) {
Output:-
Conclusion:
This program demonstrates how to model real-world entities using Object-Oriented Programming concepts such
as encapsulation and relationships between objects (Employee and Department). It focuses on data protection
and logical class design that reflects hierarchical relationships within an organization.
Experiment 11
Aim: Create an interface vehicle and classes like bicycle, car, bike etc., having common functionalities and put all
the common functionalities in the interface. Classes like Bicycle, Bike, car etc. implement all these functionalities
in their own class in their own way
Prerequisite:
1. Interfaces in Java: An interface in Java is a reference type, similar to a class, that can contain only
constants, method signatures, default methods, static methods, and nested types. Interfaces are
used to achieve abstraction and multiple inheritance.
2. Class Implementation: Understanding how classes implement interfaces and provide definitions
for the methods declared in the interface.
3. Polymorphism: Using an interface reference to refer to objects of classes that implement the
interface.
4. Abstraction: Hiding the implementation details of specific functionalities while defining their
structure.
Theory:
In this scenario, we are creating an interface called Vehicle that holds common functionalities such as start (),
stop(), and accelerate(). Each class representing a type of vehicle, such as Bicycle, Car, and Bike, will implement
the Vehicle interface and provide its own version of these functionalities.
• Interface: An interface in Java allows us to define common behaviors for unrelated classes. Since
all vehicles share basic functionalities like starting, stopping, and accelerating, these behaviors will
be declared in the Vehicle interface.
• Class Implementation: The Bicycle, Car, and Bike classes will implement the Vehicle interface and
provide their own way of defining how these behaviors work. For instance, a bicycle may have a
different implementation of acceleration compared to a car.
This approach promotes abstraction and code reusability, as common functionalities are defined once and then
implemented by multiple classes in their unique way.
Program:
interface Vehicle {
void accelerate();
void brake();
void displaySpeed();
}
speed += 5;
speed -= 5;
speed += 10;
speed -= 10;
speed += 7;
speed -= 7;
class Veh {
bicycle.accelerate();
bicycle.displaySpeed();
bicycle.turn("left");
car.accelerate();
car.displaySpeed();
car.turn("right");
Vehicle bike = new Bike();
bike.accelerate();
bike.displaySpeed();
bike.turn("left");
OUTPUT:
Conclusion:
This program demonstrates how to define common behaviors using interfaces and implement them across
different classes. It showcases the power of abstraction and polymorphism by allowing us to handle different
types of vehicles uniformly.