In this lesson, you will learn
package ch7.l7;
class Rectangle {
double length;
double width;
// Parameterized constructor
public Rectangle(double l, double w) {
length = l;
width = w;
}
//Method to Calculate Area
double calculateArea() {
return length * width;
}
}
public class RectangleMain {
public static void main(String[] args) {
Rectangle rect1 = new Rectangle(5.0, 3.0);
Rectangle rect2 = new Rectangle(5.0, 3.0);
System.out.println("Area of rect1: " + rect1.calculateArea());
System.out.println("Area of rect 2: " + rect2.calculateArea());
}
}
Area of rect1: 15.0
Area of rect 2: 450.0
class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
if (age >= 0 && age <= 150) { // Data validation
this.age = age;
} else {
System.out.println("Invalid age for student " + name + ". Setting age to 0.");
this.age = 0; // Or throw an exception
}
}
// Getters
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public class ParameterizedConstructorExample2 {
public static void main(String[] args) {
Student student1 = new Student("Alice", 20);
System.out.println("Student 1: Name = " + student1.getName() + ", Age = " + student1.getAge());
Student student2 = new Student("Bob", -5); // Invalid age
System.out.println("Student 2: Name = " + student2.getName() + ", Age = " + student2.getAge()); // Age will be 0
Student student3 = new Student("Charlie", 160); // Invalid age
System.out.println("Student 3: Name = " + student3.getName() + ", Age = " + student3.getAge()); // Age will be 0
}
}
Rectangle 1: Length = 10, Width = 5
Area = 50
Rectangle 2: Length = 7, Width = 12
Area = 84
Every topic is covered….Videos are very helpful
In this chapter i was learn about prameterized constructor .
Videos are very helpful to learn the concepts .
and the best part is sir explain the concept with the help of example .
You must be logged in to submit a review.