0% found this document useful (0 votes)
32 views

Kalpana Test11

The document provides examples of object-oriented programming concepts in Java including building classes, inheritance, encapsulation, and polymorphism. It defines classes like Car, Employee, Shape, Animal and shows how to create objects, set attributes, define and call methods on them.

Uploaded by

kalpanacse553
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Kalpana Test11

The document provides examples of object-oriented programming concepts in Java including building classes, inheritance, encapsulation, and polymorphism. It defines classes like Car, Employee, Shape, Animal and shows how to create objects, set attributes, define and call methods on them.

Uploaded by

kalpanacse553
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Java -Excersises

1. Building Blocks:
○ Create a class called Car with attributes like color, model, and year.
Define methods like startEngine, accelerate, and brake.
CODE:
package com.test;

public class Car {

String color;
String model;
int year, speed;
private boolean engineStarted;

public Car(String color, String model, int year) {


this.color = color;
this.model = model;
this.year = year;
}

public void startEngine() {


engineStarted = true;
System.out.println("Engine started.");
}

public void accelerate(int acceleration) {


if (engineStarted) {
speed += acceleration;
System.out.println("Accelerating. Current speed: " + speed +
" km/h");
} else {
System.out.println("Cannot accelerate, engine not
started.");
}
}

public void brake(int deceleration) {


if (engineStarted) {
speed = Math.max(0, speed - deceleration);
System.out.println("Braking. Current speed: " + speed + "
km/h");
} else {
System.out.println("Cannot brake, engine not started.");
}
}

public static void main(String[] args) {


Car myCar = new Car("Blue", "Sedan", 2022);
myCar.startEngine();
myCar.accelerate(30);
myCar.brake(10);
}
}

○ Create a class called Employee with attributes like name, department,


and salary. Define methods like calculateBonus and
displayDetails.

CODE:

package com.test;

public class Employee {


String name;
String department;
private double salary;

public Employee(String name, String department, double salary) {


this.name = name;
this.department = department;
this.salary = salary;
}

public double calculateBonus() {


return salary * 0.1;
}

public void displayDetails() {


System.out.println("Name: " + name);
System.out.println("Department: " + department);
System.out.println("Salary: $" + salary);
System.out.println("Bonus: $" + calculateBonus());
}

public static void main(String[] args) {


Employee emp = new Employee("Kalpana", "IT", 50000.0);
emp.displayDetails();
}
}

2. Inheritance:
○ Create a base class called Shape with an abstract method
calculateArea. Extend it to classes like Circle, Rectangle, and
Square, implementing the calculateArea method in each.
CODE:

package com.test;

abstract class Shape {


abstract double calculateArea();
}

class Circle extends Shape {


private double radius;

public Circle(double radius) {


this.radius = radius;
}

@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}

class Rectangle extends Shape {


private double length, width;

public Rectangle(double length, double width) {


this.length = length;
this.width = width;
}

@Override
public double calculateArea() {
return length * width;
}
}

class Square extends Shape {


private double side;

public Square(double side) {


this.side = side;
}

@Override
public double calculateArea() {
return side * side;
}
}

public class ShapeTest {


public static void main(String[] args) {
Circle circle = new Circle(5.0);
Rectangle rectangle = new Rectangle(4.0, 6.0);
Square square = new Square(3.0);

System.out.println("Area of Circle: " + circle.calculateArea());


System.out.println("Area of Rectangle: " + rectangle.calculateArea());
System.out.println("Area of Square: " + square.calculateArea());
}
}
○ Create a class called Animal with attributes like name and sound. Extend
it to specific animal classes like Dog, Cat, and Bird, overriding the
sound method in each subclass.
CODE:
package com.test;

class Animal {
private String name;

public Animal(String name) {


this.name = name;
}

public void makeSound() {


System.out.println("Generic animal sound");
}

public String getName() {


return name;
}

class Dog extends Animal {


public Dog(String name) {
super(name);
}
@Override
public void makeSound() {
System.out.println(getName() + " says Woof!");
}
}

class Cat extends Animal {


public Cat(String name) {
super(name);
}

@Override
public void makeSound() {
System.out.println(getName() + " says Meow!");
}
}

class Bird extends Animal {


public Bird(String name) {
super(name);
}

@Override
public void makeSound() {
System.out.println(getName() + " sings Tweet!");
}
}

public class AnimalTest {


public static void main(String[] args) {
Dog dog = new Dog("boww");
Cat cat = new Cat("cat");
Bird bird = new Bird("bird");

dog.makeSound();
cat.makeSound();
bird.makeSound();
}
}
3. Encapsulation:
○ Modify the Car class from exercise 1 to make the attributes private and provide
getter and setter methods to access and modify them.
CODE:
package com.test1;

public class Car {


private String color;
private String model;
private int year;
private boolean engineStarted;
private int speed;

public Car(String color, String model, int year) {


this.color = color;
this.model = model;
this.year = year;
}

public String getColor() {


return color;
}

public void setColor(String color) {


this.color = color;
}

public String getModel() {


return model;
}

public void setModel(String model) {


this.model = model;
}

public int getYear() {


return year;
}

public void setYear(int year) {


this.year = year;
}

public boolean isEngineStarted() {


return engineStarted;
}

public int getSpeed() {


return speed;
}

public void startEngine() {


if (!engineStarted) {
System.out.println("Engine started.");
engineStarted = true;
} else {
System.out.println("Engine is already running.");
}
}

public void accelerate(int acceleration) {


if (engineStarted) {
speed += acceleration;
System.out.println("Accelerating. Current speed: " + speed + "
km/h");
} else {
System.out.println("Cannot accelerate, engine not started.");
}
}

public void brake(int deceleration) {


if (engineStarted) {
speed = Math.max(0, speed - deceleration);
System.out.println("Braking. Current speed: " + speed + " km/h");
} else {
System.out.println("Cannot brake, engine not started.");
}
}

public static void main(String[] args) {


Car myCar = new Car("Blue", "Sedan", 2022);
myCar.startEngine();
myCar.accelerate(30);
myCar.brake(10);
System.out.println("Current color: " + myCar.getColor());
myCar.setColor("Red");
System.out.println("Updated color: " + myCar.getColor());
}
}

○ Modify the Employee class from exercise 1 to make the salary attribute private
and create a method to provide a raise while ensuring it stays within a
reasonable range.
CODE:
package com.test1;

public class Employee {


private String name;
private String department;
private double salary;

public Employee(String name, String department, double salary) {


this.name = name;
this.department = department;
this.salary = salary;
}

public double getSalary() {


return salary;
}

private void setSalary(double salary) {


this.salary = salary;
}

public void giveRaise(double percent) {


double raiseAmount = getSalary() * (percent / 100);

if (raiseAmount >= 0.01 * getSalary() && raiseAmount <= 0.2 *


getSalary()) {
setSalary(getSalary() + raiseAmount);
System.out.println("Raise of " + percent + "% given. New salary:
$" + getSalary());
} else {
System.out.println("Invalid raise percentage. Please provide a
percentage between 1% and 20%.");
}
}

public void displayDetails() {


System.out.println("Name: " + name);
System.out.println("Department: " + department);
System.out.println("Salary: $" + getSalary());
}

public static void main(String[] args) {


Employee emp = new Employee("Kalpana", "IT", 50000.0);
emp.displayDetails();

emp.giveRaise(10);
emp.displayDetails();
}
}
4. Polymorphism:
○ Create an interface called Drawable with a method draw. Extend it to classes
like Shape, Circle, and Rectangle, overriding the draw method in each to
display their specific representation.

CODE:
package com.test1;

interface Drawable {
void draw();
}

class Shape implements Drawable {


@Override
public void draw() {
System.out.println("Drawing a generic shape");
}
}

class Circle implements Drawable {


private double radius;

public Circle(double radius) {


this.radius = radius;
}

@Override
public void draw() {
System.out.println("Drawing a circle with radius " + radius);
}
}
class Rectangle implements Drawable {
private double length, width;

public Rectangle(double length, double width) {


this.length = length;
this.width = width;
}

@Override
public void draw() {
System.out.println("Drawing a rectangle with length " + length + " and
width " + width);
}
}

public class DrawingTest {


public static void main(String[] args) {
Drawable shape = new Shape();
Drawable circle = new Circle(5.0);
Drawable rectangle = new Rectangle(4.0, 6.0);

shape.draw();
circle.draw();
rectangle.draw();
}
}
○ Create an abstract class called AnimalSound with an abstract method
makeSound. Extend it to specific animal classes like Dog, Cat, and Bird,
overriding the makeSound method to play the animal's sound (using
System.out.println for simplicity).
CODE:
package com.test1;

abstract class AnimalSound {


public abstract void makeSound();
}

class Dog extends AnimalSound {


@Override
public void makeSound() {
System.out.println("Dog barks: Woof! Woof!");
}
}

class Cat extends AnimalSound {


@Override
public void makeSound() {
System.out.println("Cat meows: Meow! Meow!");
}
}

class Bird extends AnimalSound {


@Override
public void makeSound() {
System.out.println("Bird sings: Tweet! Tweet!");
}
}

public class AnimalTestSound {


public static void main(String[] args) {
AnimalSound dog = new Dog();
AnimalSound cat = new Cat();
AnimalSound bird = new Bird();

dog.makeSound();
cat.makeSound();
bird.makeSound();
}
}
Advanced:

5. Abstraction:
○ Create an abstract class called PaymentProcessor with an abstract
method processPayment. Extend it to concrete classes like
CreditCardPaymentProcessor and PayPalPaymentProcessor,
implementing the processPayment method for each specific payment
method.

CODE: package com.test1;


abstract class PaymentProcessor {
public abstract void processPayment(double amount);
}

class CreditCardPaymentProcessor extends PaymentProcessor {


private String creditCardNumber;

public CreditCardPaymentProcessor(String creditCardNumber) {


this.creditCardNumber = creditCardNumber;
}

@Override
public void processPayment(double amount) {
System.out.println("Processing credit card payment of $" + amount + "
with card number: " + creditCardNumber);
// Additional credit card payment processing logic
}
}

class PayPalPaymentProcessor extends PaymentProcessor {


private String paypalEmail;

public PayPalPaymentProcessor(String paypalEmail) {


this.paypalEmail = paypalEmail;
}

@Override
public void processPayment(double amount) {
System.out.println("Processing PayPal payment of $" + amount + " with
email: " + paypalEmail);

}
}

public class PaymentProcessorTest {


public static void main(String[] args) {
PaymentProcessor creditCardProcessor = new
CreditCardPaymentProcessor("1234-5678-9101-1121");
PaymentProcessor paypalProcessor = new
PayPalPaymentProcessor("[email protected]");

creditCardProcessor.processPayment(100.0);
paypalProcessor.processPayment(50.0);
}
}
○ Create an interface called ShapeFactory with a method getShape.
Implement it for different shapes, e
CODE: package com.test2;

interface Shape {
void draw();
}

class Circle implements Shape {


@Override
public void draw() {
System.out.println("Drawing a circle");
}
}

class Rectangle implements Shape {


@Override
public void draw() {
System.out.println("Drawing a rectangle");
}
}

class Triangle implements Shape {


@Override
public void draw() {
System.out.println("Drawing a triangle");
}
}

interface ShapeFactory {
Shape getShape();
}

class CircleFactory implements ShapeFactory {


@Override
public Shape getShape() {
return new Circle();
}
}

class RectangleFactory implements ShapeFactory {


@Override
public Shape getShape() {
return new Rectangle();
}
}

class TriangleFactory implements ShapeFactory {


@Override
public Shape getShape() {
return new Triangle();
}
}

public class ShapeFactoryTest {


public static void main(String[] args) {
ShapeFactory circleFactory = new CircleFactory();
ShapeFactory rectangleFactory = new RectangleFactory();
ShapeFactory triangleFactory = new TriangleFactory();

Shape circle = circleFactory.getShape();


Shape rectangle = rectangleFactory.getShape();
Shape triangle = triangleFactory.getShape();

circle.draw();
rectangle.draw();
triangle.draw();
}
}

Create a Class:

Create a class named Time with the following attributes:

● hour: Integer (0-23)


● minute: Integer (0-59)
● second: Integer (0-59)

2. Define Constructors:

● No-argument constructor: This constructor should initialize all attributes to 0.


● Parameterized constructor: This constructor should take three integers as
arguments for hour, minute, and second, respectively, and perform validation
to ensure the values are within the valid ranges mentioned above. If any value is
outside the range, throw an IllegalArgumentException with an appropriate
message.

3. Create a Main Method:

● In the main method, prompt the user to enter the hour, minute, and second
values through the console using Scanner.
● Create a new Time object using either the no-argument constructor or the
parameterized constructor based on user input.
○ If the user chooses the parameterized constructor and enters invalid
values, handle the IllegalArgumentException and prompt the user
to re-enter the values.
● Display the created Time object by printing its hour, minute, and second in a
formatted way (e.g., "HH:MM:SS").

CODE:
package com.test2;

import java.util.Scanner;

public class Time {


private int hour;
private int minute;
private int second;

public Time() {
this.hour = 0;
this.minute = 0;
this.second = 0;
}

public Time(int hour, int minute, int second) {


if (isValidHour(hour) && isValidMinute(minute) &&
isValidSecond(second)) {
this.hour = hour;
this.minute = minute;
this.second = second;
} else {
throw new IllegalArgumentException("Invalid time values. Hour,
minute, and second must be within valid ranges.");
}
}

private boolean isValidHour(int hour) {


return hour >= 0 && hour <= 23;
}

private boolean isValidMinute(int minute) {


return minute >= 0 && minute <= 59;
}

private boolean isValidSecond(int second) {


return second >= 0 && second <= 59;
}

public void displayTime() {


System.out.printf("%02d:%02d:%02d\n", hour, minute, second);
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter hour (0-23): ");


int hour = scanner.nextInt();

System.out.print("Enter minute (0-59): ");


int minute = scanner.nextInt();

System.out.print("Enter second (0-59): ");


int second = scanner.nextInt();

try {
Time userTime = new Time(hour, minute, second);
userTime.displayTime();
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
System.out.println("Please enter valid time values.");
} finally {
scanner.close();
}
}
}

If user enters correct Values:


If users enter incorrect values:

You might also like