Write a program to define user defined exceptions and raise them as per the requirements.
Code:
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
class User {
private String name;
private int age;
public User(String name, int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or older.");
}
this.name = name;
this.age = age;
}
public void displayUserInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
try {
User user1 = new User("John", 25);
user1.displayUserInfo();
User user2 = new User("Alice", 16); // This will throw an exception
user2.displayUserInfo(); // This won't be executed due to the exception
} catch (InvalidAgeException e) {
System.out.println("InvalidAgeException caught: " + e.getMessage());
}
}
}
Write a program to implement the concepts of Abstract classes and
methods.
// Abstract class
abstract class Shape {
// Abstract method
abstract double calculateArea();
// Concrete method
void display() {
System.out.println("This is a shape.");
}
}
// Concrete subclass Circle
class Circle extends Shape {
double radius;
Circle(double radius) {
this.radius = radius;
}
// Implementation of abstract method
@Override
double calculateArea() {
return Math.PI * radius * radius;
}
}
// Concrete subclass Rectangle
class Rectangle extends Shape {
double length;
double width;
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
// Implementation of abstract method
@Override
double calculateArea() {
return length * width;
}
}
public class Main {
public static void main(String[] args) {
// Creating objects of concrete subclasses
Circle circle = new Circle(5);
Rectangle rectangle = new Rectangle(4, 6);
// Calling methods on objects
circle.display();
System.out.println("Area of circle: " + circle.calculateArea());
rectangle.display();
System.out.println("Area of rectangle: " + rectangle.calculateArea());
}
}
Comments
Post a Comment