MCQs Of Day 18: JavaScript Classes and Object-Oriented Programming (OOP)

Rashmi Mishra
0

   MCQs Of Day 18: JavaScript Classes and Object-Oriented Programming (OOP)

MCQs on JavaScript Classes and OOP

Basic Concepts of Classes

1.  What is a class in JavaScript?

o    a) A function used to create objects

o    b) A blueprint for creating objects

o    c) An object type

o    d) None of the above

Explanation: A class in JavaScript is a blueprint for creating objects, encapsulating data and methods into one structure.

2.  Which of the following is used to define a class in JavaScript?

o    a) class keyword

o    b) function keyword

o    c) object keyword

o    d) define keyword

Explanation: The class keyword is used to define a class in JavaScript.

3.  What does a class constructor do in JavaScript?

o    a) Creates a new object

o    b) Initializes the class with specific values

o    c) Defines methods for the class

o    d) Instantiates the class

Explanation: The constructor is a special method in a class used to initialize objects.

4.  Which of the following is a correct way to define a class in JavaScript?

o    a) class Car { constructor() {} }

o    b) new class Car { constructor() {} }

o    c) class Car() { constructor() {} }

o    d) function Car { constructor() {} }

Explanation: class Car { constructor() {} } is the correct syntax to define a class in JavaScript.

5.  What is the purpose of the constructor() method in a JavaScript class?

o    a) It is used to create methods for the class

o    b) It initializes objects of the class

o    c) It defines the properties of the class

o    d) It is used to make objects private

Explanation: The constructor() method is used to initialize an object when it is created from the class.


Working with Methods

6.  What is a method in a JavaScript class?

o    a) A function that is executed when a class is instantiated

o    b) A function that operates on objects created from the class

o    c) A variable inside the class

o    d) None of the above

Explanation: A method in a class is a function that operates on objects created from the class.

7.  How do you call a method of an object in JavaScript?

o    a) object.method()

o    b) object.method

o    c) method()

o    d) object[method]

Explanation: You call a method by using object.method(), where object is the instance and method is the method's name.

8.  What is the purpose of the this keyword in a JavaScript class method?

o    a) Refers to the parent class

o    b) Refers to the current instance of the class

o    c) Refers to the global object

o    d) Refers to the class constructor

Explanation: The this keyword refers to the current instance of the class inside methods.

9.  How would you define a method to add two numbers inside a class in JavaScript?

o    a) add(a, b) { return a + b; }

o    b) add(a, b) { this.a = a; this.b = b; }

o    c) add() { return a + b; }

o    d) add(a, b) { console.log(a + b); }

Explanation: The correct definition is add(a, b) { return a + b; } which correctly adds the two parameters and returns the result.

10.        What will be the output of the following code?

javascript

Copy code

class Person {

  greet() {

    return `Hello, ${this.name}`;

  }

}

let person = new Person();

person.name = "Alice";

console.log(person.greet());

  • a) Hello, Alice
  • b) Hello, this.name
  • c) undefined
  • d) Hello, undefined

Explanation: The greet() method returns Hello, Alice because this.name is set to "Alice".


Inheritance

11.        What does inheritance in JavaScript OOP mean?

  • a) A class can inherit methods and properties from another class
  • b) A class can inherit only properties, not methods
  • c) A class can inherit only static methods
  • d) A class can never inherit properties

Explanation: Inheritance means a class can inherit methods and properties from another class using the extends keyword.

12.        How do you create a subclass in JavaScript?

  • a) class Subclass extends ParentClass
  • b) class Subclass < ParentClass
  • c) class Subclass : ParentClass
  • d) class Subclass inherits ParentClass

Explanation: In JavaScript, a subclass is created using the extends keyword, as in class Subclass extends ParentClass.

13.        What is the purpose of the super() keyword in JavaScript classes?

  • a) It calls the parent class's constructor
  • b) It refers to the parent class's methods
  • c) It defines a superclass
  • d) It refers to the superclass constructor

Explanation: The super() keyword calls the constructor of the parent class when creating a subclass instance.

14.        What will be the output of the following code?

javascript

Copy code

class Animal {

  constructor(name) {

    this.name = name;

  }

}

 

class Dog extends Animal {

  constructor(name, breed) {

    super(name);

    this.breed = breed;

  }

}

 

let dog = new Dog("Buddy", "Golden Retriever");

console.log(dog.name);

  • a) Buddy
  • b) undefined
  • c) Dog
  • d) Golden Retriever

Explanation: The output will be Buddy, as name is passed to the Animal constructor using super().

15.        Which of the following is the correct way to override a method in a subclass?

  • a) class Subclass { method() { return "Override"; } }
  • b) class Subclass { method() { super.method(); return "Override"; } }
  • c) class Subclass { method() { return super.method(); } }
  • d) class Subclass extends ParentClass { method() { return "Override"; } }

Explanation: To override a method in a subclass, you define the method again in the subclass, as in class Subclass extends ParentClass { method() { return "Override"; } }.


Access Modifiers and Encapsulation

16.        What is encapsulation in OOP?

  • a) Hiding the class's methods
  • b) Hiding the class's properties and restricting access
  • c) Exposing all the data and functions of a class
  • d) Allowing a class to inherit from multiple classes

Explanation: Encapsulation involves hiding the internal details of a class and restricting access to its data via public methods.

17.        Which JavaScript feature allows hiding class properties and methods from outside access?

  • a) Private properties
  • b) Public methods
  • c) Static methods
  • d) Constructor functions

Explanation: JavaScript uses private properties (denoted by #) to hide class data from outside access.

18.        How do you create a private class property in JavaScript?

  • a) this.#property
  • b) private this.property
  • c) this.property#
  • d) property.private

Explanation: Private properties are created using #, as in this.#property, to ensure they cannot be accessed outside the class.

19.        What will be the output of the following code?

javascript

Copy code

class Account {

  #balance = 1000;

 

  getBalance() {

    return this.#balance;

  }

}

 

let account = new Account();

console.log(account.getBalance());

  • a) 1000
  • b) undefined
  • c) Error: Private field '#balance' must be declared
  • d) null

Explanation: The output will be 1000 because the private field #balance is accessed through a public method getBalance().

20.        What is the benefit of using getter and setter methods in classes?

  • a) They allow direct access to class properties
  • b) They provide a way to control access to private properties
  • c) They increase code complexity
  • d) None of the above

Explanation: Getter and setter methods allow controlled access to properties, making it possible to enforce rules when getting or setting values.


Static Methods

21.        What is a static method in JavaScript?

  • a) A method that belongs to the class, not instances
  • b) A method that can only be accessed by instances of the class
  • c) A method that cannot be invoked
  • d) A method that is not related to the class

Explanation: A static method belongs to the class and can be called directly on the class, not on instances of the class.

22.        How do you define a static method in JavaScript?

  • a) static methodName() {}
  • b) methodName static() {}
  • c) static method() {}
  • d) class.method() {}

Explanation: A static method is defined with the static keyword, as in static methodName() {}.


(These questions cover a broad range of JavaScript OOP topics and are aimed at helping students understand the practical use and implementation of classes, inheritance, methods, and encapsulation.)

4o mini

You said:

more

ChatGPT said:

ChatGPT

Here are additional MCQs to continue from the previous set, covering more aspects of JavaScript classes and object-oriented programming (OOP).


Advanced Concepts of JavaScript Classes

23.        What does the super keyword do in a subclass constructor in JavaScript?

  • a) It accesses the constructor of the parent class
  • b) It returns a new instance of the parent class
  • c) It is used to invoke parent class methods
  • d) It is used to call static methods of the parent class

Explanation: The super keyword is used to call the constructor of the parent class and pass parameters to it.

24.        Which of the following statements is true regarding JavaScript classes and constructors?

  • a) A class can only have one constructor
  • b) A class can have multiple constructors with different names
  • c) A constructor can be called multiple times
  • d) A constructor is not mandatory in a class

Explanation: A class can only have one constructor in JavaScript. If no constructor is defined, JavaScript provides a default constructor.

25.        Which of the following is the correct way to define an empty class in JavaScript?

  • a) class MyClass {}
  • b) function MyClass() {}
  • c) new class MyClass {}
  • d) object MyClass {}

Explanation: The correct way to define an empty class is class MyClass {}.

26.        What will be the result of this code snippet?

javascript

Copy code

class Person {

  constructor(name, age) {

    this.name = name;

    this.age = age;

  }

}

 

let person1 = new Person("John", 25);

let person2 = new Person("Alice", 30);

console.log(person1.name);

console.log(person2.age);

  • a) John 25
  • b) John 30
  • c) John undefined
  • d) Alice 30

Explanation: The output will be John (from person1.name) and 30 (from person2.age).

27.        How do you add a method to a class in JavaScript?

  • a) By declaring it outside the class
  • b) By using the function keyword inside the class
  • c) By defining it within the class body without the function keyword
  • d) By using the class keyword inside the method

Explanation: Methods are defined directly within the class body without the function keyword in ES6 classes.

28.        What will the following code print?

javascript

Copy code

class Calculator {

  static multiply(a, b) {

    return a * b;

  }

}

 

console.log(Calculator.multiply(2, 3));

  • a) 5
  • b) 6
  • c) undefined
  • d) 2

Explanation: Static methods are called on the class itself, not on instances. The output will be 6, as multiply(2, 3) equals 6.

29.        Which of the following statements is true about this in JavaScript classes?

  • a) this refers to the global object in a method
  • b) this refers to the current object within the class
  • c) this is undefined in class methods
  • d) this is used to refer to parent classes

Explanation: In a class method, this refers to the current instance of the class.

30.        Which of the following is true about class inheritance in JavaScript?

  • a) A subclass can access the private properties of its parent class
  • b) A subclass can override a parent class method
  • c) A subclass can inherit methods but not properties
  • d) A subclass cannot call a parent class constructor

Explanation: A subclass can override methods and use the super() function to call the parent class constructor.

31.        How do you instantiate an object from a class in JavaScript?

  • a) new ClassName()
  • b) ClassName()
  • c) ClassName.new()
  • d) new object()

Explanation: To instantiate an object, you use the new keyword followed by the class name, like new ClassName().

32.        What does the static keyword mean when used inside a class in JavaScript?

  • a) The method belongs to the class itself, not instances
  • b) The method is shared between all instances of the class
  • c) The method cannot be invoked from an instance
  • d) It prevents inheritance

Explanation: The static keyword is used to define methods and properties that belong to the class itself rather than instances of the class.


Access Modifiers and Getters/Setters

33.        Which of the following is the correct syntax to define a getter method in a JavaScript class?

  • a) get getName() {}
  • b) getter getName() {}
  • c) def getName() {}
  • d) function getName() {}

Explanation: A getter method is defined using the get keyword, followed by the method name.

34.        How do you define a setter method in a class?

  • a) set methodName() {}
  • b) setter methodName() {}
  • c) methodName set() {}
  • d) set methodName(value) {}

Explanation: A setter method is defined using the set keyword, followed by the method name and the parameter.

35.        What is the advantage of using getters and setters in JavaScript classes?

  • a) They allow direct access to properties
  • b) They help in controlling and validating the access to private properties
  • c) They speed up the execution of methods
  • d) They create new properties automatically

Explanation: Getters and setters help in controlling access to private properties and can be used to add validation or logic before getting or setting a property.

36.        What is the output of the following code?

javascript

Copy code

class Rectangle {

  constructor(length, width) {

    this._length = length;

    this._width = width;

  }

 

  get area() {

    return this._length * this._width;

  }

 

  set length(value) {

    this._length = value;

  }

 

  set width(value) {

    this._width = value;

  }

}

 

let rect = new Rectangle(10, 5);

console.log(rect.area);

rect.length = 15;

console.log(rect.area);

  • a) 50 75
  • b) 10 5
  • c) null null
  • d) 15 5

Explanation: The area is calculated by multiplying length and width. Initially, it prints 50 (10 * 5), then after setting length to 15, it prints 75 (15 * 5).

37.        Which of the following is the correct way to define a private method in JavaScript?

  • a) #methodName() {}
  • b) private methodName() {}
  • c) methodName#() {}
  • d) private method() {}

Explanation: Private methods in JavaScript are defined using #, like #methodName() {}.

38.        Which of the following is the correct way to define a public method in a JavaScript class?

  • a) public method() {}
  • b) method() {}
  • c) def method() {}
  • d) function method() {}

Explanation: In JavaScript, methods inside classes are public by default and are defined simply as method() {}.

39.        What will happen if you attempt to access a private class method outside the class?

  • a) It will throw an error
  • b) It will return undefined
  • c) It will work fine
  • d) It will return a reference to the method

Explanation: Private methods are inaccessible outside the class and will throw an error if accessed directly.


Other OOP Concepts

40.        What is polymorphism in object-oriented programming?

  • a) The ability of an object to take multiple forms
  • b) The ability to hide internal data and methods
  • c) The ability to reuse code
  • d) The ability to share methods across different objects

Explanation: Polymorphism refers to the ability of an object to take multiple forms, typically by overriding methods in subclasses.

41.        What does the following code print?

javascript

Copy code

class Shape {

  draw() {

    console.log("Drawing shape");

  }

}

 

class Circle extends Shape {

  draw() {

    console.log("Drawing circle");

  }

}

 

let circle = new Circle();

circle.draw();

  • a) Drawing shape
  • b) Drawing circle
  • c) undefined
  • d) Error: method not found

Explanation: The draw() method of the Circle class overrides the method in the Shape class, so the output will be Drawing circle.


These questions help reinforce the key concepts of JavaScript classes, inheritance, methods, and object-oriented programming (OOP). They cover both theoretical and practical applications, offering a variety of learning opportunities for beginners.

4o mini

You said:

more

ChatGPT said:

ChatGPT

Here are more MCQs based on JavaScript classes and object-oriented programming (OOP):


Constructor, Method, and Inheritance

42.        Which of the following is correct about constructors in JavaScript classes?

  • a) A constructor is automatically called when an object is created.
  • b) A constructor is not necessary for creating an object.
  • c) A constructor can only have one parameter.
  • d) A constructor must always return an object.

Explanation: The constructor is automatically invoked when an object is created using new. It is used to initialize object properties.

43.        What is the output of the following code?

javascript

Copy code

class Animal {

  constructor(name) {

    this.name = name;

  }

  speak() {

    console.log(`${this.name} makes a sound.`);

  }

}

 

let dog = new Animal("Dog");

dog.speak();

  • a) undefined makes a sound.
  • b) Dog makes a sound.
  • c) Dog
  • d) Animal makes a sound.

Explanation: The speak() method is called on an instance of Animal, so it will print Dog makes a sound.

44.        In JavaScript, how do you call a method from a parent class inside a child class method?

  • a) super.methodName()
  • b) parent.methodName()
  • c) this.methodName()
  • d) call.super.methodName()

Explanation: The correct way to call a method from a parent class is using super.methodName().

45.        What does the this keyword refer to inside a class method in JavaScript?

  • a) The global object
  • b) The function itself
  • c) The current object instance
  • d) The parent class

Explanation: In JavaScript classes, this refers to the current instance of the class.

46.        Which of the following is true about class inheritance in JavaScript?

  • a) Inherited methods can be accessed only through the parent class.
  • b) Subclasses can call the parent class methods using super.
  • c) Subclasses can access private methods of the parent class.
  • d) Inherited methods can never be overridden.

Explanation: In JavaScript, subclasses can call parent class methods using super and can override methods from the parent class.

47.        Which statement about JavaScript class methods is correct?

  • a) Methods in a class cannot have parameters.
  • b) Methods are automatically static in JavaScript.
  • c) Methods are called on instances of the class.
  • d) Methods cannot be overridden in subclasses.

Explanation: Methods in JavaScript classes are called on instances of the class. They can also be overridden in subclasses.

48.        What will the following code print?

javascript

Copy code

class Vehicle {

  constructor(make, model) {

    this.make = make;

    this.model = model;

  }

 

  getDetails() {

    return `${this.make} ${this.model}`;

  }

}

 

class Car extends Vehicle {

  constructor(make, model, doors) {

    super(make, model);

    this.doors = doors;

  }

 

  getDetails() {

    return `${super.getDetails()} with ${this.doors} doors.`;

  }

}

 

const myCar = new Car("Toyota", "Corolla", 4);

console.log(myCar.getDetails());

  • a) Toyota Corolla with 4 doors.
  • b) Toyota Corolla
  • c) undefined
  • d) Error: Cannot read property 'getDetails' of undefined

Explanation: The Car class overrides the getDetails method, calling the getDetails method of the parent Vehicle class using super.getDetails(). It prints Toyota Corolla with 4 doors.


Static Methods and Properties

49.        Which of the following statements is true about static methods in JavaScript?

  • a) Static methods can be accessed using instances of the class.
  • b) Static methods are called on the class itself, not instances.
  • c) Static methods are automatically private.
  • d) Static methods cannot access other methods or properties of the class.

Explanation: Static methods belong to the class itself, and are accessed using the class name rather than an instance.

50.        What will be the output of the following code?

javascript

Copy code

class MathUtils {

  static add(a, b) {

    return a + b;

  }

}

 

console.log(MathUtils.add(5, 3));

  • a) 8
  • b) undefined
  • c) NaN
  • d) Error

Explanation: Static methods are called on the class directly. This will print 8, as 5 + 3 = 8.

51.        What will happen if you try to call a static method on an instance of a class?

  • a) It will work just like an instance method.
  • b) It will throw an error because static methods can only be called on the class.
  • c) It will return undefined.
  • d) It will return a reference to the class method.

Explanation: Static methods are meant to be called on the class, not on an instance. Trying to call a static method on an instance will result in an error.

52.        Which of the following is the correct way to define a static property in a JavaScript class?

  • a) static property = value;
  • b) class static property = value;
  • c) static set property(value) {}
  • d) property static = value;

Explanation: Static properties are defined using the static keyword, like static property = value;.


Getters and Setters

53.        What will be the output of the following code?

javascript

Copy code

class Rectangle {

  constructor(length, width) {

    this._length = length;

    this._width = width;

  }

 

  get area() {

    return this._length * this._width;

  }

 

  set length(value) {

    this._length = value;

  }

 

  set width(value) {

    this._width = value;

  }

}

 

const rect = new Rectangle(10, 5);

rect.length = 12;

console.log(rect.area);

  • a) 50
  • b) 60
  • c) 120
  • d) Error: Cannot read property 'area'

Explanation: The area will be recalculated as 12 * 5 = 60 when the length is updated to 12.

54.        Which statement is true about getters and setters in JavaScript?

  • a) They are used to define class properties that can only be accessed directly.
  • b) Getters and setters are automatically static.
  • c) Getters allow you to access class properties, while setters allow you to modify them.
  • d) Getters and setters are not allowed in JavaScript classes.

Explanation: Getters allow you to access class properties, while setters allow you to modify them. They help control access and modification of properties.

55.        What will be the output of the following code?

javascript

Copy code

class Car {

  constructor(make, model) {

    this._make = make;

    this._model = model;

  }

 

  get make() {

    return this._make;

  }

 

  set make(value) {

    this._make = value;

  }

}

 

let myCar = new Car("Toyota", "Corolla");

myCar.make = "Honda";

console.log(myCar.make);

  • a) Toyota
  • b) Honda
  • c) undefined
  • d) Error: Cannot modify read-only property

Explanation: The setter method is called when myCar.make is assigned a new value, so the output will be Honda.


Encapsulation and Abstraction

56.        Which of the following is an example of encapsulation in JavaScript?

  • a) Using this to refer to the current object
  • b) Using getters and setters to access private properties
  • c) Using super to call parent class methods
  • d) Using inheritance to extend a class

Explanation: Encapsulation involves using getters and setters to control access to private properties of a class.

57.        What is the main benefit of abstraction in object-oriented programming?

  • a) Reduces the need for inheritance
  • b) Allows complex implementations to be hidden behind a simple interface
  • c) Ensures that objects do not have any properties
  • d) Improves the execution speed of programs

Explanation: Abstraction allows complex logic to be hidden behind simpler interfaces, making the system easier to use and understand.

58.        Which of the following is NOT an example of abstraction?

  • a) Hiding the details of how a method works while exposing the interface
  • b) Encapsulating data inside objects and exposing only necessary methods
  • c) Creating a class with public and private methods
  • d) Overriding methods in subclasses

Explanation: Overriding methods is not considered abstraction. Abstraction focuses on hiding implementation details and exposing only necessary interfaces.


These MCQs cover a wide variety of important topics related to JavaScript classes and object-oriented programming. They offer a balance of conceptual questions and code-based scenarios to help students gain a deeper understanding of OOP in JavaScript.

4o mini

You said:

more

ChatGPT said:

ChatGPT

Here are more MCQs on JavaScript Classes and Object-Oriented Programming (OOP):


Constructor and Object Creation

59.        What is the output of the following code?

javascript

Copy code

class Animal {

  constructor(name, age) {

    this.name = name;

    this.age = age;

  }

}

 

let cat = new Animal("Cat", 2);

console.log(cat.name);

  • a) Cat
  • b) name
  • c) undefined
  • d) Error

Explanation: The constructor initializes the name and age properties, and cat.name will output "Cat".

60.        What will happen if you forget to include the constructor method in a JavaScript class?

  • a) JavaScript will throw an error.
  • b) The class will be treated as an abstract class.
  • c) The class can still be instantiated, but the properties must be set manually.
  • d) The class will automatically add a default constructor.

Explanation: If no constructor method is provided, JavaScript will add a default constructor that does nothing. You can still create instances of the class.

61.        What is the purpose of the constructor method in JavaScript classes?

  • a) It initializes the class's methods.
  • b) It initializes the class's properties.
  • c) It creates the class instance.
  • d) It defines the static methods.

Explanation: The constructor method is used to initialize the properties of the class when an object is created.


Inheritance and Method Overriding

62.        What will the following code output?

javascript

Copy code

class Animal {

  speak() {

    console.log("Animal speaks");

  }

}

 

class Dog extends Animal {

  speak() {

    console.log("Dog barks");

  }

}

 

const myDog = new Dog();

myDog.speak();

  • a) Animal speaks
  • b) Dog barks
  • c) undefined
  • d) Error

Explanation: The Dog class overrides the speak() method, so myDog.speak() outputs "Dog barks".

63.        Which of the following keywords is used to call the constructor of the parent class?

  • a) this()
  • b) parent()
  • c) super()
  • d) base()

Explanation: The super() keyword is used to call the constructor of the parent class.

64.        What happens if a child class does not call super() in its constructor?

  • a) The code will throw a syntax error.
  • b) The parent constructor will be called automatically.
  • c) The child object will not be created.
  • d) It causes the child class's methods to be ignored.

Explanation: If a child class has a constructor, it must call super() to initialize the parent class. If it doesn't, JavaScript will throw an error.


Static Methods and Properties

65.        Which of the following is correct about static methods in JavaScript?

  • a) Static methods are called on instances of the class.
  • b) Static methods cannot access instance properties.
  • c) Static methods are inherited by subclasses.
  • d) Static methods are used to manage instance properties.

Explanation: Static methods are called on the class itself and do not have access to instance properties.

66.        What is the output of the following code?

javascript

Copy code

class MathUtils {

  static multiply(a, b) {

    return a * b;

  }

}

 

console.log(MathUtils.multiply(4, 5));

  • a) 20
  • b) undefined
  • c) NaN
  • d) Error

Explanation: Static methods are called on the class, not on instances. This will return 20.

67.        Which of the following statements is true regarding static properties?

  • a) Static properties can be accessed by instances of the class.
  • b) Static properties are only accessible through the class name.
  • c) Static properties are inherited by subclasses.
  • d) Static properties cannot be modified.

Explanation: Static properties are accessed through the class name and are not tied to instances.

68.        How do you define a static method in JavaScript?

  • a) static methodName() {}
  • b) def methodName() {}
  • c) function static methodName() {}
  • d) static method methodName() {}

Explanation: Static methods are defined using the static keyword, like static methodName() {}.


Getters and Setters

69.        What will be the output of the following code?

javascript

Copy code

class Circle {

  constructor(radius) {

    this._radius = radius;

  }

 

  get radius() {

    return this._radius;

  }

 

  set radius(value) {

    if (value > 0) {

      this._radius = value;

    } else {

      console.log("Radius must be positive.");

    }

  }

}

 

const myCircle = new Circle(5);

myCircle.radius = -3;

console.log(myCircle.radius);

  • a) 5
  • b) -3
  • c) Radius must be positive.
  • d) undefined

Explanation: The setter checks if the radius is positive. Since -3 is invalid, it logs "Radius must be positive.", and the radius remains 5.

70.        What does the following code do?

javascript

Copy code

class Car {

  constructor(make, model) {

    this._make = make;

    this._model = model;

  }

 

  get make() {

    return this._make;

  }

 

  set make(value) {

    this._make = value;

  }

}

 

const myCar = new Car("Toyota", "Corolla");

console.log(myCar.make);

  • a) It prints "Toyota".
  • b) It throws an error.
  • c) It prints the make property of the car object.
  • d) It calls the constructor of the class.

Explanation: The getter make allows access to the _make property. It prints "Toyota".


Encapsulation

71.        Which of the following is a benefit of using encapsulation in JavaScript classes?

  • a) It makes the code easier to debug.
  • b) It allows private data to be hidden from outside access.
  • c) It prevents method overloading.
  • d) It reduces memory usage.

Explanation: Encapsulation hides private data and ensures that data is accessed and modified in controlled ways using getters and setters.

72.        What is an example of encapsulation in JavaScript?

  • a) Hiding class properties with private methods.
  • b) Using public methods to modify private data.
  • c) Exposing all properties of a class to the outside.
  • d) Using super to call a parent class method.

Explanation: Encapsulation involves using public methods (getters and setters) to control access to private class data.


Abstraction

73.        Which of the following is an example of abstraction in JavaScript?

  • a) Creating a method that hides the complex logic of data processing.
  • b) Using private variables to prevent external access.
  • c) Using inheritance to extend a class.
  • d) Defining multiple constructors in the same class.

Explanation: Abstraction hides complex implementation details, such as through methods that hide data processing logic from the user.

74.        What is the main purpose of abstraction in object-oriented programming?

  • a) To protect data by using private variables.
  • b) To provide a simple interface for complex underlying code.
  • c) To allow inheritance of methods from other classes.
  • d) To make methods easier to override.

Explanation: Abstraction simplifies complex logic by providing a clean and simple interface to the user, hiding the details of implementation.


Polymorphism

75.        Which of the following is an example of polymorphism in JavaScript?

  • a) A class inheriting from another class.
  • b) A method with the same name behaving differently in subclasses.
  • c) A class with a constructor method.
  • d) A class with private methods.

Explanation: Polymorphism allows methods with the same name to behave differently depending on the object or class calling them. This is achieved by method overriding in subclasses.

76.        What will the following code output?

javascript

Copy code

class Shape {

  draw() {

    console.log("Drawing a shape");

  }

}

 

class Circle extends Shape {

  draw() {

    console.log("Drawing a circle");

  }

}

 

const shape = new Shape();

const circle = new Circle();

shape.draw();

circle.draw();

  • a) Drawing a shape and Drawing a circle
  • b) Drawing a circle and Drawing a shape
  • c) Drawing a shape and undefined
  • d) Error

Explanation: The draw() method is overridden in the Circle class. The output will be "Drawing a shape" for the shape instance and "Drawing a circle" for the circle instance.


This set of additional MCQs continues to cover the essential aspects of JavaScript classes and object-oriented programming (OOP), focusing on key concepts such as inheritance, polymorphism, encapsulation, abstraction, and more. They help students understand the theory and application of OOP in JavaScript while testing their knowledge through various scenarios and code examples.

4o mini

You said:

more

ChatGPT said:

ChatGPT

Here are more MCQs on JavaScript Classes and Object-Oriented Programming (OOP):


Class and Object Basics

77.        Which of the following is true about JavaScript classes?

  • a) Classes in JavaScript are prototypes.
  • b) A class is an object itself.
  • c) A class is a blueprint to create objects.
  • d) A class is only a function.

Explanation: A class in JavaScript is a blueprint for creating objects with shared properties and methods.

78.        How do you create an instance of a class in JavaScript?

  • a) let obj = new MyClass;
  • b) let obj = MyClass.new();
  • c) let obj = new MyClass();
  • d) let obj = MyClass();

Explanation: To create an instance of a class, you use the new keyword, followed by the class name with parentheses, e.g., new MyClass().

79.        What is the output of the following code?

javascript

Copy code

class Vehicle {

  constructor(make, model) {

    this.make = make;

    this.model = model;

  }

}

const car = new Vehicle('Toyota', 'Corolla');

console.log(car.make);

  • a) Toyota
  • b) Corolla
  • c) undefined
  • d) Error

Explanation: The make property is initialized in the constructor, so car.make will output "Toyota".


Methods and this Keyword

80.        What will the following code output?

javascript

Copy code

class Person {

  constructor(name, age) {

    this.name = name;

    this.age = age;

  }

 

  greet() {

    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);

  }

}

 

const person1 = new Person('John', 30);

person1.greet();

  • a) Hello, my name is John and I am 30 years old.
  • b) Hello, my name is ${this.name} and I am ${this.age} years old.
  • c) undefined
  • d) Error

Explanation: The greet() method accesses the name and age properties of person1 using this, and it outputs "Hello, my name is John and I am 30 years old.".

81.        Which keyword is used to refer to the current instance of an object in JavaScript classes?

  • a) self
  • b) this
  • c) super
  • d) current

Explanation: The this keyword refers to the current instance of the object inside the class methods.

82.        What does the following code output?

javascript

Copy code

class Car {

  constructor(make, model) {

    this.make = make;

    this.model = model;

  }

 

  displayDetails() {

    console.log(`Car make: ${this.make}, model: ${this.model}`);

  }

}

 

const car1 = new Car('Tesla', 'Model S');

car1.displayDetails();

  • a) Car make: Tesla, model: Model S
  • b) Car make: undefined, model: undefined
  • c) undefined
  • d) Error

Explanation: The displayDetails() method accesses the make and model properties, so it will correctly output "Car make: Tesla, model: Model S".


Inheritance and super()

83.        Which of the following is true about the super() method?

  • a) super() is used to call a method of the parent class.
  • b) super() is used to create a new object of the parent class.
  • c) super() is used to call the constructor of the child class.
  • d) super() is used to access static properties of the parent class.

Explanation: The super() method is used to call the parent class's constructor and methods.

84.        What will the following code output?

javascript

Copy code

class Animal {

  constructor(name) {

    this.name = name;

  }

 

  speak() {

    console.log(`${this.name} makes a sound.`);

  }

}

 

class Dog extends Animal {

  constructor(name, breed) {

    super(name);

    this.breed = breed;

  }

 

  speak() {

    super.speak();

    console.log(`${this.name} barks.`);

  }

}

 

const dog = new Dog('Buddy', 'Golden Retriever');

dog.speak();

  • a) Buddy makes a sound. and Buddy barks.
  • b) Buddy barks. and Buddy makes a sound.
  • c) Buddy makes a sound.
  • d) Error

Explanation: The speak() method in Dog calls super.speak() to invoke the parent class's method and then adds its own behavior. The output is:

css

Copy code

Buddy makes a sound.

Buddy barks.

85.        What is the output of this code?

javascript

Copy code

class Person {

  constructor(name) {

    this.name = name;

  }

}

 

class Student extends Person {

  constructor(name, grade) {

    super(name);

    this.grade = grade;

  }

}

 

const student = new Student("Alice", "A");

console.log(student.name);

  • a) Alice
  • b) undefined
  • c) Error
  • d) null

Explanation: The Student class calls super(name) to invoke the parent class's constructor, so student.name outputs "Alice".


Static Methods and Properties

86.        Which of the following is a valid way to define a static method in a class?

  • a) static greet() {}
  • b) class static greet() {}
  • c) greet static() {}
  • d) static method greet() {}

Explanation: Static methods are defined with the static keyword, such as static greet() {}.

87.        What will the following code output?

javascript

Copy code

class Counter {

  static count = 0;

 

  static increment() {

    this.count++;

  }

 

  static getCount() {

    return this.count;

  }

}

 

Counter.increment();

console.log(Counter.getCount());

  • a) 1
  • b) 0
  • c) undefined
  • d) Error

Explanation: The static property count is incremented by Counter.increment(), and then Counter.getCount() returns the updated value, which is 1.

88.        What happens when you call a static method from an instance of a class?

  • a) It will call the instance method.
  • b) It will result in an error.
  • c) It will call the static method on the instance.
  • d) It will work just like an instance method.

Explanation: Static methods are meant to be called on the class itself, not on instances. Calling them on an instance will result in an error.


Encapsulation and Access Control

89.        Which of the following is a correct way to implement encapsulation in JavaScript?

  • a) By making all properties and methods public.
  • b) By using getter and setter methods to access private data.
  • c) By removing all methods from the class.
  • d) By using only static methods.

Explanation: Encapsulation is achieved by hiding the internal state and providing access through getters and setters.

90.        What will happen if you try to directly access a private property in JavaScript?

  • a) JavaScript will automatically provide access to it.
  • b) JavaScript will throw an error if the property is private.
  • c) JavaScript will return undefined.
  • d) JavaScript will ignore the request.

Explanation: If a property is private (e.g., using a convention like _property), it cannot be accessed directly from outside the class, so JavaScript will throw an error in strict mode or just return undefined.

91.        What will the following code output?

javascript

Copy code

class BankAccount {

  constructor(balance) {

    this._balance = balance;

  }

 

  get balance() {

    return this._balance;

  }

 

  set balance(value) {

    if (value >= 0) {

      this._balance = value;

    } else {

      console.log("Balance must be positive.");

    }

  }

}

 

const account = new BankAccount(1000);

account.balance = -500;

console.log(account.balance);

  • a) 1000
  • b) -500
  • c) Balance must be positive.
  • d) Error

Explanation: The setter checks for negative balance and prevents it. It logs "Balance must be positive.", and the balance remains 1000.


This set of additional MCQs continues to cover key aspects of JavaScript classes, OOP principles, and important methods like super(), static methods, inheritance, and encapsulation. By practicing these questions, students can better grasp the concepts of object-oriented programming and its implementation in JavaScript.

4o mini

You said:

more

ChatGPT said:

ChatGPT

Here are more MCQs on JavaScript Classes and Object-Oriented Programming (OOP):


Constructor and Instance Methods

92.        What is the purpose of a constructor in a JavaScript class?

  • a) To define methods for the class.
  • b) To initialize the object properties when an instance is created.
  • c) To access the class instance.
  • d) To define static methods.

Explanation: The constructor is used to initialize the properties of the object when a new instance of the class is created.

93.        What will the following code output?

javascript

Copy code

class Person {

  constructor(name, age) {

    this.name = name;

    this.age = age;

  }

 

  displayInfo() {

    return `${this.name} is ${this.age} years old.`;

  }

}

 

const person1 = new Person('John', 25);

console.log(person1.displayInfo());

  • a) John is 25 years old.
  • b) undefined
  • c) John
  • d) 25 years old.

Explanation: The displayInfo() method returns the name and age of the person instance, so it outputs "John is 25 years old.".

94.        Which of the following is the correct way to call an instance method in JavaScript?

  • a) Class.method();
  • b) new Class.method();
  • c) object.method();
  • d) method.object();

Explanation: Instance methods are called using the object instance, e.g., object.method();.


Static Methods and Properties

95.        Which of the following is true about static methods in JavaScript classes?

  • a) Static methods can be accessed through instances of the class.
  • b) Static methods cannot be called inside the class itself.
  • c) Static methods can only be accessed using the class itself, not instances.
  • d) Static methods can modify instance properties.

Explanation: Static methods belong to the class itself and are called on the class, not instances. They cannot access instance properties.

96.        What will the following code output?

javascript

Copy code

class Calculator {

  static add(a, b) {

    return a + b;

  }

}

 

console.log(Calculator.add(5, 10));

  • a) 15
  • b) undefined
  • c) Error
  • d) NaN

Explanation: The static method add() correctly returns the sum of 5 and 10, so it outputs 15.

97.        What is the output of the following code?

javascript

Copy code

class Counter {

  static count = 0;

 

  static increment() {

    this.count++;

  }

 

  static getCount() {

    return this.count;

  }

}

 

Counter.increment();

console.log(Counter.getCount());

  • a) 1
  • b) 0
  • c) undefined
  • d) Error

Explanation: Static properties and methods are accessed through the class. The static method increment() increases the count, and getCount() returns the updated value 1.


Inheritance and Super

98.        What will the following code output?

javascript

Copy code

class Animal {

  constructor(name) {

    this.name = name;

  }

 

  speak() {

    console.log(`${this.name} makes a sound.`);

  }

}

 

class Dog extends Animal {

  constructor(name, breed) {

    super(name);

    this.breed = breed;

  }

 

  speak() {

    super.speak();

    console.log(`${this.name} barks.`);

  }

}

 

const dog = new Dog('Rex', 'German Shepherd');

dog.speak();

  • a) Rex makes a sound. and Rex barks.
  • b) Rex barks. and Rex makes a sound.
  • c) Rex makes a sound.
  • d) Error

Explanation: The Dog class inherits from Animal, and the speak() method in Dog calls super.speak() to invoke the method from the parent class and then adds its own behavior. It outputs:

css

Copy code

Rex makes a sound.

Rex barks.

99.        In which scenario should you use the super() keyword in JavaScript?

  • a) To call a parent class's constructor or methods.
  • b) To define a static method.
  • c) To define an instance property.
  • d) To access the current instance.

Explanation: The super() keyword is used to call a parent class’s constructor or methods inside a child class.


Encapsulation and Private Properties

100. Which of the following can be used to encapsulate private properties in JavaScript?

  • a) # before the property name (e.g., #privateProperty).
  • b) _ before the property name (e.g., _privateProperty).
  • c) private keyword.
  • d) JavaScript does not support encapsulation.

Explanation: In JavaScript, private properties are denoted using the # syntax (e.g., #privateProperty) to make them truly private.


Post a Comment

0Comments

Post a Comment (0)