Assignments Of Day 18: JavaScript Classes and Object-Oriented Programming (OOP)
Assignment 1: Create a Class and Instantiate an Object
Problem: Create a class Book with the following properties: title, author, and year. Use the constructor to initialize these properties. Then, create an instance of the class and display its properties.
Step-by-Step Solution:
1. Define the Book class with a constructor.
o The class will accept parameters for title, author, and year to initialize the properties.
2. Create an instance of the Book class.
o After defining the class, instantiate it using the new keyword.
3. Display the properties.
o Use console.log() to display the values of the properties.
Code:
javascript
Copy code
class Book {
constructor(title, author, year) {
this.title = title;
this.author = author;
this.year = year;
}
}
let myBook = new Book("The Great Gatsby", "F. Scott Fitzgerald", 1925);
console.log(myBook.title); // The Great Gatsby
console.log(myBook.author); // F. Scott Fitzgerald
console.log(myBook.year); // 1925
Explanation:
- The Book class is defined with a constructor that initializes the title, author, and year properties.
- The myBook instance is created with specific values, and the properties are accessed using console.log().
Assignment 2: Add a Method to the Class
Problem: Add a method getBookInfo to the Book class that returns a string with the full details of the book. For example: "The Great Gatsby by F. Scott Fitzgerald, published in 1925."
Step-by-Step Solution:
1. Add the getBookInfo method to the class.
o This method should return a string that combines the title, author, and year properties.
2. Call the method on the instance.
o After creating the instance, call getBookInfo() to see the formatted string.
Code:
javascript
Copy code
class Book {
constructor(title, author, year) {
this.title = title;
this.author = author;
this.year = year;
}
getBookInfo() {
return `${this.title} by ${this.author}, published in ${this.year}.`;
}
}
let myBook = new Book("The Great Gatsby", "F. Scott Fitzgerald", 1925);
console.log(myBook.getBookInfo()); // The Great Gatsby by F. Scott Fitzgerald, published in 1925.
Explanation:
- The getBookInfo() method is added to the Book class. It uses template literals to create a string that includes the book’s details.
- The myBook.getBookInfo() method returns the formatted string.
Assignment 3: Using the this Keyword
Problem: Create a Car class with properties: make, model, and year. Add a method carDetails() that prints out the details of the car using the this keyword.
Step-by-Step Solution:
1. Define the Car class with a constructor.
o The constructor will accept the parameters make, model, and year to initialize the properties.
2. Add a carDetails() method.
o Use the this keyword to access the properties within the method.
3. Instantiate a Car object and call the method.
Code:
javascript
Copy code
class Car {
constructor(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
carDetails() {
console.log(`Car: ${this.year} ${this.make} ${this.model}`);
}
}
let myCar = new Car("Toyota", "Corolla", 2020);
myCar.carDetails(); // Car: 2020 Toyota Corolla
Explanation:
- The Car class is created with a constructor that initializes the properties make, model, and year.
- The carDetails() method uses this to access the properties and displays the car details.
Assignment 4: Class Inheritance
Problem: Create a Person class with properties name and age. Then, create a subclass Employee that inherits from the Person class and adds an additional property position. Add a method getEmployeeInfo() to display the employee’s name, age, and position.
Step-by-Step Solution:
1. Create the Person class.
o Define the name and age properties in the constructor.
2. Create the Employee class.
o Use extends to inherit from the Person class.
o Add a constructor for position.
3. Add the getEmployeeInfo() method.
Code:
javascript
Copy code
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
class Employee extends Person {
constructor(name, age, position) {
super(name, age); // Call the parent class constructor
this.position = position;
}
getEmployeeInfo() {
console.log(`${this.name}, ${this.age} years old, works as a ${this.position}.`);
}
}
let employee1 = new Employee("John", 30, "Software Developer");
employee1.getEmployeeInfo(); // John, 30 years old, works as a Software Developer.
Explanation:
- The Employee class inherits from the Person class using extends.
- The super() function calls the constructor of the parent class (Person), and the position is added as an additional property.
- The getEmployeeInfo() method outputs the employee's details.
Assignment 5: Demonstrate the this Keyword Inside Methods
Problem: In the Student class, define properties name, age, and grade. Add a method updateGrade that allows updating the student's grade using this. Demonstrate how this works in the method.
Step-by-Step Solution:
1. Define the Student class with a constructor.
o Initialize name, age, and grade properties.
2. Add the updateGrade() method.
o Use this to update the grade property.
3. Create an instance and update the grade.
Code:
javascript
Copy code
class Student {
constructor(name, age, grade) {
this.name = name;
this.age = age;
this.grade = grade;
}
updateGrade(newGrade) {
this.grade = newGrade;
console.log(`${this.name}'s grade has been updated to ${this.grade}.`);
}
}
let student1 = new Student("Alice", 20, "B");
student1.updateGrade("A"); // Alice's grade has been updated to A.
Explanation:
- The Student class contains a constructor to initialize name, age, and grade.
- The updateGrade() method uses this.grade to modify the student's grade and then prints the updated grade.
Assignment 6: Overriding Methods in Subclasses
Problem: Create a Vehicle class with a startEngine() method that outputs "Engine started". Create a subclass ElectricCar that overrides the startEngine() method to output "Electric engine started". Demonstrate polymorphism by calling startEngine() on both classes.
Step-by-Step Solution:
1. Define the Vehicle class with a method.
o Create the method startEngine() in the Vehicle class.
2. Create the ElectricCar subclass that overrides the method.
o Override the startEngine() method in the ElectricCar subclass.
3. Instantiate both classes and call the method.
Code:
javascript
Copy code
class Vehicle {
startEngine() {
console.log("Engine started");
}
}
class ElectricCar extends Vehicle {
startEngine() {
console.log("Electric engine started");
}
}
let vehicle = new Vehicle();
vehicle.startEngine(); // Engine started
let electricCar = new ElectricCar();
electricCar.startEngine(); // Electric engine started
Explanation:
- The ElectricCar class overrides the startEngine() method of the Vehicle class, demonstrating polymorphism where the same method name behaves differently in different classes.
4o mini
You said:
more
ChatGPT said:
ChatGPT
Additional Assignments on JavaScript Classes and Object-Oriented Programming (OOP)
Assignment 7: Static Methods in JavaScript Classes
Problem: Create a class MathOperations that contains a static method add(a, b) to return the sum of two numbers. Demonstrate how to call this static method without creating an instance of the class.
Step-by-Step Solution:
1. Define a class with a static method.
o The add(a, b) method will be defined as a static method using the static keyword.
2. Call the static method.
o Static methods are accessed via the class name, not through an instance.
Code:
javascript
Copy code
class MathOperations {
static add(a, b) {
return a + b;
}
}
let result = MathOperations.add(5, 10); // 15
console.log(result); // 15
Explanation:
- The add(a, b) method is static, meaning it is called directly on the MathOperations class without needing to instantiate it.
- The static method calculates the sum of two numbers and returns it.
Assignment 8: Using Getter and Setter Methods
Problem: Create a class Person with properties name and age. Use getter and setter methods to access and modify the values of these properties. The setter for age should only allow values between 0 and 120.
Step-by-Step Solution:
1. Define the Person class with properties name and age.
o Use a constructor to initialize these properties.
2. Add getter and setter methods for name and age.
o The setter for age ensures that only valid values are accepted.
3. Create an instance and modify properties using getter and setter methods.
Code:
javascript
Copy code
class Person {
constructor(name, age) {
this.name = name;
this._age = age; // Use an underscore to denote a private variable
}
get age() {
return this._age;
}
set age(value) {
if (value >= 0 && value <= 120) {
this._age = value;
} else {
console.log("Invalid age");
}
}
get name() {
return this.name;
}
set name(value) {
this.name = value;
}
}
let person1 = new Person("Alice", 30);
person1.age = 35; // Update the age using the setter method
console.log(person1.age); // 35
person1.age = 150; // Invalid age
Explanation:
- The getter and setter methods allow controlled access to the age property. The setter includes validation to ensure the age is within a valid range.
- The name property is also controlled via getter and setter, though no validation is applied.
Assignment 9: Constructor Chaining with super()
Problem: Create a Person class with name and age. Then create a subclass Student that adds an additional grade property. Use the super() method to call the parent class's constructor and initialize both name and age.
Step-by-Step Solution:
1. Define the Person class.
o The Person class should accept name and age in the constructor.
2. Create the Student subclass that extends Person.
o Use super() to call the parent class constructor and initialize the properties.
3. Create an instance of Student and display the properties.
Code:
javascript
Copy code
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
class Student extends Person {
constructor(name, age, grade) {
super(name, age); // Call the parent class constructor
this.grade = grade;
}
getStudentInfo() {
console.log(`${this.name}, Age: ${this.age}, Grade: ${this.grade}`);
}
}
let student1 = new Student("Bob", 20, "A");
student1.getStudentInfo(); // Bob, Age: 20, Grade: A
Explanation:
- The Student subclass extends Person and calls the parent constructor (super(name, age)) to initialize inherited properties.
- The getStudentInfo() method is specific to the Student class and displays the student's details.
Assignment 10: Inheritance and Method Overriding
Problem: Create a Shape class with a method area(). Then create a Rectangle subclass that inherits from Shape and overrides the area() method to calculate the area of a rectangle. Instantiate both classes and demonstrate method overriding.
Step-by-Step Solution:
1. Define the Shape class with a method area().
o The area() method will return a message indicating that it's a shape.
2. Create the Rectangle subclass.
o Override the area() method to calculate the area of a rectangle.
3. Instantiate both classes and call the area() method.
Code:
javascript
Copy code
class Shape {
area() {
console.log("This is a shape");
}
}
class Rectangle extends Shape {
constructor(width, height) {
super(); // Call the parent class constructor
this.width = width;
this.height = height;
}
area() {
return this.width * this.height; // Override the area method
}
}
let shape = new Shape();
shape.area(); // This is a shape
let rectangle = new Rectangle(10, 5);
console.log("Area of Rectangle: " + rectangle.area()); // Area of Rectangle: 50
Explanation:
- The Shape class provides a generic area() method.
- The Rectangle subclass overrides the area() method to calculate the area based on width and height.
- The super() function is used to call the parent class constructor.
Assignment 11: Class with Private Properties (Encapsulation)
Problem: Create a BankAccount class that has private properties for balance and accountNumber. Use getter and setter methods to access and update the balance. Ensure the balance can only be modified through the deposit and withdraw methods.
Step-by-Step Solution:
1. Define the BankAccount class.
o Include private properties _balance and _accountNumber.
2. Use setter and getter methods for controlled access.
o The deposit() and withdraw() methods will update the balance.
3. Create an instance and perform operations.
Code:
javascript
Copy code
class BankAccount {
constructor(accountNumber, initialBalance) {
this._accountNumber = accountNumber;
this._balance = initialBalance;
}
get balance() {
return this._balance;
}
deposit(amount) {
if (amount > 0) {
this._balance += amount;
} else {
console.log("Deposit amount must be positive");
}
}
withdraw(amount) {
if (amount <= this._balance && amount > 0) {
this._balance -= amount;
} else {
console.log("Insufficient funds or invalid amount");
}
}
}
let account = new BankAccount("12345", 1000);
account.deposit(500); // Deposit 500
console.log(account.balance); // 1500
account.withdraw(200); // Withdraw 200
console.log(account.balance); // 1300
Explanation:
- The BankAccount class uses private properties for balance (_balance) and account number (_accountNumber).
- The deposit() and withdraw() methods modify the balance, ensuring that only valid transactions are performed.
- The balance is accessed through a getter method, but direct manipulation is not possible.
Assignment 12: Using Inheritance with Multiple Subclasses
Problem: Create a base class Appliance that has a property brand and a method turnOn(). Then create two subclasses WashingMachine and Refrigerator that inherit from Appliance. Each subclass should override the turnOn() method to perform a specific action.
Step-by-Step Solution:
1. Define the Appliance class.
o The Appliance class will have a property brand and a generic turnOn() method.
2. Create subclasses WashingMachine and Refrigerator.
o Each subclass will override the turnOn() method.
3. Instantiate both subclasses and demonstrate the overridden method.
Code:
javascript
Copy code
class Appliance {
constructor(brand) {
this.brand = brand;
}
turnOn() {
console.log("Turning on the appliance");
}
}
class WashingMachine extends Appliance {
turnOn() {
console.log("Starting the washing cycle...");
}
}
class Refrigerator extends Appliance {
turnOn() {
console.log("Cooling the refrigerator...");
}
}
let washingMachine = new WashingMachine("LG");
washingMachine.turnOn(); // Starting the washing cycle...
let refrigerator = new Refrigerator("Samsung");
refrigerator.turnOn(); // Cooling the refrigerator...
Explanation:
- The Appliance class is a generic base class that provides a default turnOn() method.
- Both WashingMachine and Refrigerator override turnOn() to provide their own specific behavior.
- This demonstrates method overriding and inheritance in JavaScript classes.
