JAVA Lab Sample Questions
1) create an interface Movable with methods moveForward() and moveBackward().
Create another interface Steerable that extends Movable and adds methods
turnLeft() and turnRight(). Implement Steerable in a Robot class. Create an instance
of Robot and call all the methods.
Ans.:
// [Link] Interface
public interface Movable {
void moveForward();
void moveBackward();
}
// [Link] Interface
public interface Steerable extends Movable {
void turnLeft();
void turnRight();
}
// [Link] Class
public class Robot implements Steerable {
@Override
public void moveForward() {
[Link]("Robot is moving forward.");
}
@Override
public void moveBackward() {
[Link]("Robot is moving backward.");
}
@Override
public void turnLeft() {
[Link]("Robot is turning left.");
}
@Override
public void turnRight() {
[Link]("Robot is turning right.");
}
}
// [Link] Class
public class Main {
public static void main(String[] args) {
// Create Robot instance
Robot robot = new Robot();
// Call all methods
[Link]();
[Link]();
[Link]();
[Link]();
}
}
2. Create an abstract class named Transport with an abstract method start(). Create
an interface named Fuelable with methods refuel() and checkFuelLevel().
Implement these in a class named Car. The Car class should provide its own
implementation of start(), refuel(), and checkFuelLevel(). Create an instance of
Car and call the methods to demonstrate their functionality.
// [Link]
public abstract class Transport {
public abstract void start();
}
// [Link]
public interface Fuelable {
void refuel();
void checkFuelLevel();
}
// [Link]
public class Car extends Transport implements Fuelable {
@Override
public void start() {
[Link]("Car is starting.");
}
@Override
public void refuel() {
[Link]("Refueling the car.");
}
@Override
public void checkFuelLevel() {
[Link]("Checking the car's fuel level.");
}
}
// [Link]
public class Main {
public static void main(String[] args) {
// Create Car instance
Car car = new Car();
// Call methods
[Link]();
[Link]();
[Link]();
}
}
3. Create an abstract class Fruit with an abstract method taste(). Create two
subclasses: Apple and Orange. Each subclass should implement the taste() method to
describe the taste of that fruit (e.g., "Sweet" for Apple, "Tangy" for Orange). Create
instances of Apple and Orange, invoke the taste() method on each object, and print the
taste.
// [Link]
public abstract class Fruit {
public abstract void taste();
}
// [Link]
public class Apple extends Fruit {
@Override
public void taste() {
[Link]("Sweet");
}
}
// [Link]
public class Orange extends Fruit {
@Override
public void taste() {
[Link]("Tangy");
}
}
// [Link]
public class Main {
public static void main(String[] args) {
// Create Apple instance
Fruit apple = new Apple();
[Link](); // Output: Sweet
// Create Orange instance
Fruit orange = new Orange();
[Link](); // Output: Tangy
}
}