Learn Object-Oriented Programming in Java Educative Quiz Answers

Get Learn Object-Oriented Programming in Java Educative Quiz Answers

Object-oriented programming (OOP) has been around for decades. As the original object-oriented language, Java is a mainstay in the world of computer programming.

Having a foundation in OOP Java concepts will allow you to write cleaner, more modular, and more reusable code, as well as make it easier for you to understand the codebases of different companies you might be interested in joining.

Starting with the basics and reviewing complex topics like inheritance and polymorphism, this course is filled with illustrations, exercises, quizzes, and hands-on challenges. You’ll walk away with an understanding of classes and objects behavior and be able to easily create simple, efficient, reusable and secure code.

Enroll on Educative

Quiz 1: Classes and Objects

Q1. The attributes of a class can be divided into the following two parts:

  • Methods and Constructors
  • Method and Access Modifiers
  • Methods and Fields
  • None of the above

Q2. What is the output of the code below?

class Score {
  private int num;
  public Score() {
    this.num = num;
  }
  
  public int getNum(){
    return this.num;
  }
}

class Demo {
  public static void main(String args[]) {
    Score sc = new Score(5);
    System.out.println(sc.getNum());
  }
}
  • 5
  • 0
  • Compile error
  • Runtime error

Q3. If you don’t define any constructor, the Java compiler will insert a default constructor for you.

  • True
  • False

Q4. Data members are usually kept:

  • Private
  • Public
  • Does not matter

Q5. Member functions are usually kept:

  • Private
  • Public
  • Does not matter

Quiz 2: Data Hiding

Q1. What are the two components of data hiding?

  • Abstraction and Composition
  • Encapsulation and Abstraction
  • Encapsulation and Functions

Q2. As a rule of thumb, the data members of a class should be declared as

  • private
  • public
  • protected

Q3. Data hiding makes sure that the irrelevant details of the class implementation are hidden from the user.

  • True
  • False

Q4. To let a class communicate with the outside world we implement

  • data members
  • public methods
  • private methods

Object Oriented Programming in Java – Exam 1:

Q1. A Java program can not exist without which one of the following?

  • An Object
  • A Class
  • Method
  • Variables

Q2. What type of parameter passing is used by Java?

  • Pass by value
  • Pass by reference

Q3. Select the option that shows the correct blueprint for all classes declared in Java.

  • ClassName { // Description of the instance variables. // Description of the constructors. // Description of the methods. }
  • Class ClassName { // Description of the instance variables. // Description of the constructors. // Description of the methods. }
  • class ClassName { // Description of the instance variables. // Description of the constructors. // Description of the methods. }
  • class ClassName { public static void main ( String[] args ) { // Entire program logic goes here } }

Q4. How many objects are created in the following main() function?

    public static void main(String[] args) {

        Stack stack1;
        Stack stack2 = new Stack();

    }
  • 1
  • 2
  • 3
  • None of the above

Q5. If the access modifier is not mentioned in the definition of a member of a class (instance variable or method), then the member has ____________ access.

  • default
  • public
  • private
  • global

Q6. Which of the following is valid for a class member with a private access modifier?

  • It can be used in only one place in a program.
  • It can only be used by other private members of other classes.
  • It can only have one instance, no matter how many objects are instantiated.
  • It can be used only in methods that are members of that class.

Q7. Hiding the details of an object from the other parts of a program is called ____________.

  • Data Mining
  • Private Access
  • Encapsulation
  • Static Data

Q8. What will be the output of the following program?

class Assessment
{
   static int marks=0;
   public void increment()
   {
       marks++;
   }
   public static void main(String args[])
   {
       Assessment a1 = new Assessment();
       Assessment a2 = new Assessment();
       a1.increment();
       a2.increment();
       a2.increment();
       System.out.println("A1: marks are = " + a1.marks);
       System.out.println("A2: marks are = " + a2.marks);
   }
}
  • A1: marks are = 3 A2: marks are = 3
  • A1: marks are = 1 A2: marks are = 2
  • A1: marks are = 0 A2: marks are = 2
  • A1: marks are = 2 A2: marks are = 2

Q9: What will be the output of the following program?

class DisplayOutput {

    public void display() {
        System.out.println("Nothing");
    }
    
    public void display(int x) { 
        System.out.println(x);
    }
   
    public int display(int y){
        System.out.println(y);
    }

}

class Quiz {
  
    public static void main(String[] args) {

        DisplayOutput out = new DisplayOutput();

        int x = 10;
        int y = 20;

        out.display(x);
        out.display();
        out.display(y);

    }
  
}

  • 10 Nothing 20
  • Compilation Error as there are three methods with the same name.
  • Runtime error as the program does not know which display() method to call.
  • Compilation error since the overloaded method with the same parameters has a different return type.

Q10. The given program is valid and will output the following: i = 10 s = static i = 10 s = static

class Example{
  static int i = 10;
  static String s = "static";
  
  static void display()
  {
     System.out.println("i = "+ i);
     System.out.println("s = "+ s);
  }
  void func()
  {
      display();
  }

  
  public static void main(String args[])
  {
      Example obj = new Example();

      obj.funcn();
      display();
   }
}
  • True
  • False

Q11. The value of a `final` variable can not be changed after initialization.

  • True
  • False

Q12. The public access modifier means that a method or a member variable of an object can be accessed by code outside of the class.

  • True
  • False

Q13. Getters and Setters are generally used to access or modify the public data members of a class.

  • True
  • False

Q14. In this coding exercise, you are required to implement a class called GroceryList that will keep track of groceries to buy. This class will have the following member variables:

  1. numberOfItems: This variable will be equal to current grocery items inside the list.
  2. items: It will also contain an array of strings that holds the names of items. You can assume that it can hold 20 items at maximum.

The GroceryList class should also contain the following methods:

  1. insertItem: This function will take the name of an item as input and insert it into the grocery list.
  2. printList: This function will not take in any input. It will print out the items currently present in the list. Make sure that it does not print any empty strings.

The following code in the main() method should give the output mentioned below.

Input
GroceryList gc = new GroceryList();
gc.insertItem("Onion");
gc.insertItem("Garlic");
gc.insertItem("Bread");
gc.printList();
Output
Onion
Garlic
Bread
Solution:

Q15. In this exercise, you are required to implement a Patient class as a part of the hospital management system. As you might be aware, a patient’s personal information is confidential, therefore, we must use encapsulation in this class. The Patient class should contain the following private attributes:

  1. name: A string containing the name of the patient.
  2. id: An integer containing the assigned patient ID number by the hospital.
  3. doctor: A string containing the name of the doctor who is treating the patient.

Note: You will have to add getters and setters for each attribute.

The class will have the following methods:

  • getName
  • setName
  • getId
  • setId
  • setDoctor
  • getDoctor
Solution:

Quiz 3: Inheritance

Q1. Which keyword is used to derive a class from another class?

  • super
  • this
  • extends
  • extend

Q2. A subclass can use all the fields and methods of the superclass directly which are:

  • Private
  • Non-private
  • Both

Q3.

class A {
    
    int i;
    public A(int i)
    {
        this.i=i; 
    }
    
}
class B extends A{
    
    int j;
    public B(int j)
    {
        this.j=j;
    }
    
}

The above code won’t compile because

  • The fields are not private
  • Subclass is not calling the parent class constructor
  • Superclass is not calling the subclass constructor
  • The fields are not initialized

Q4. The super keyword is used to call?

  • The current class methods
  • The parent class methods
  • Any method can be called
  • The child class methods

Q5. Calls to constructors using this( ) and super( ) can be written inside

  • The static blocks only
  • The constructors only
  • A constructor at the same time
  • Anywhere in a class

Quiz 4: Polymorphism

Q1. What is the output of the following piece of code?


class Base {
  
  public Base() {}
  public void print() { 
    System.out.println("Base");
  }
}

class Derived extends Base {

  public Derived() {}
  public void print() {
    System.out.println("Derived");
  }
}

class Demo {
  
  public static void main(String args[]) {
    Base obj = new Derived();
    obj.print();
  }
}
  • Base
  • Base
    Derived
  • Derived
  • None of the above

Q2. What is the output of the following piece of code?


class Base {

  public Base() {}
  public void print() { 
    System.out.println("Base");
  }
}

class Derived extends Base {

  public Derived() {}
  public void print() {
    super.print();
    System.out.println("Derived");
  }
}

class Demo {
  public static void main(String args[]) {
    Base obj = new Derived();
    obj.print();
  }
}
  • Base
  • Base
    Derived
  • Derived
  • None of the above

Q3. We can not override the final method.

  • True
  • False

Q4. Following condition/s must be satisified for the Method Overriding:

  • Method name must be the same
  • Parameters must be the same
  • Return type must be the same
  • All of the above

Q5. We can not overload a method in the same class.

  • True
  • False

Quiz 5: Abstract Classes and Interfaces

Q1. Abstraction in Object Oriented Programming refers to

  • “What an object does?” rather than “How it does?”
  • “How an object does?” rather than “What it does?”
  • “What an object does?” and “How it does?”
  • None of the above

Q2. An abstract method can be declared inside

  • abstract classes only
  • interfaces only
  • both interfaces & abstract classes

Q3. An abstract class cannot be instantiated so it cannot have a constructor?

  • True
  • False

Q4. An interface can extend from

  • abstract classes only
  • interfaces only
  • both abstract classes and interfaces
  • none of the above

Quiz 6: Composition, Aggregation and Association

Q1. In a part-of relationship between two classes:

  • Both classes must be a part of the other.
  • One class must be a part of the other.
  • Both classes should be parts of a third class.

Q2. What kind of relationship does composition use?

  • Part-of
  • Has-A
  • None of the above

Q3. What should we call it when an object has its own lifecycle and child object cannot belong to another parent object?

  • Association
  • Composition
  • Aggregation
  • Inheritance

Q4. What kind of relationship does association follow?

  • Part-of
  • Has-a
  • It’s a generic term used for both of the above

Object Oriented Programming in Java – Exam 2:

Q1. Which of the following option shows the correct syntax for declaring a new class Volvo based on the superclass Car?

  • class Volvo implements Car { //additional definitions }
  • class Volvo isA Car { //additional definitions }
  • class Volvo defines Car { //additional definitions }
  • class Volvo extends Car { //additional definitions }

Q2. Suppose you have to program a library management system. This system has three classes: BookFictionalBook, and NonFictionalBook. Which of the following would be the most rational relationship between these classes?

  • The Book is the superclass. The FictionalBook and NonFictionalBook are subclasses of the Book.
  • The FictionalBook is the superclass. The Book and FictionalBook are subclasses of the FictionalBook.
  • The Book, NonFictionalB, and FictionalBookare sibling classes.
  • The Book is the superclass. The FictionalBook is subclasses of the Book. The NonFictionalBook is a subclass of FictionalBook.

Q3. Which of the following is not an advantage of inheritance?

  • Re-usability
  • Extensibility
  • Data Hiding
  • Decoupling

Q4. Which of the following options is true regarding the abstract methods?

  • An abstract class can only define abstract methods.
  • The abstract class can define both types of methods, however, at a time it can only define all abstract or all non-abstract methods.
  • An abstract class can define both types of methods, however, the subclasses do not inherit the abstract methods.
  • The abstract class can define both types of methods and they are also inherited by subclasses.

Q5. Suppose we have a class called Car which has two subclasses called Volvo and Volkswagen. The Volvo class also has a subclass called Sedan. Now, consider the following code:

Car myCar;
Volvo myVolvo = new Volvo();
Volkswagen myVolkswagen = new Volkswagen();
Sedan mysedan = new Sedan();

Which one of the following lines of code will give an error?

  • myCar = myVolvo;
  • mySedan = myVolkswagen;
  • mySedan = myVolvo;
  • myCar = myVolkswagen;

Q6. Which of the following is the parent class of all the classes in Java by default?

  • Object
  • Root
  • System
  • Class

Q7. What would be the output of the following code?

abstract class Book {


  protected String name;
  protected String author;


  public Book(String name, String author) {
    this.name = name;
    this.author = author;
  }


  public abstract String getDetails();

}


class MyBook extends Book {

  public MyBook(String name, String author) {
    super(name, author); 
  }

public static void main(String args[]) {
    Book myBook = new MyBook("Harry Potter", "J.k. Rowling");
    System.out.println(myBook.getDetails());
  }

}
  • Harry Potter by J.k. Rowling
  • Compilation Error

Q8. Can we simulate multiple inheritance in Java? If so, then how?

  • Yes, we can use classes to create multiple inheritance in Java using the extends keyword.
  • Yes, we can simulate multiple inheritance in Java using interfaces.
  • No, it is not possible to implement multiple inheritance in Java.

Q9. Take a look at the given code and then select the option that best describes the code.

class Room {
    int number;
    String phone;
    boolean vacancy;
   
}

class Hotel extends Customer {
    String name;
    Room[] rooms;
    String address;
    
}

  • This code shows an example of an aggregation
  • This code is an example of a composition

Q10. An interface can not contain method bodies.

  • True
  • False

Q11. An interface can not inherit from another interface

  • True
  • False

Q12. Match the statements shown in the left column with the concepts in the right column that best define the mentioned scenario.

  • The object has its own lifecycle and child object cannot belong to another parent object
  • The child object gets killed if the parent object is killed
  • The child and parent objects have their own lifecycles and their is no owner
  • The parents reference could be used to refer to the child object
  • Association
  • Composition
  • Aggregation
  • Polymorphism

Answers:

  • The object has its own lifecycle and child object cannot belong to another parent object –
  • The child object gets killed if the parent object is killed –
  • The child and parent objects have their own lifecycles and their is no owner –
  • The parents reference could be used to refer to the child object –

Q13. For this coding exercise, you are required to implement the train management component. You are given three entities: TrainPassengerTrain, and CargoTrain.

  • Train: This should be an abstract class, therefore, its object can not be created. It should contain the following attributes:
    • name variable
    • capacity variable
    • getDetails() function
  • PassengerTrain: This should be a Java class that inherits all properties of the Train class.
  • CargoTrain: This should also be a Java class that inherits all characteristics of the Train class.

The getDetials() method should also be defined in the inherited classes. For a passenger train named “Orient Express”, which contains the capacity of “300” people, this function should return the following string:

Orient Express is a passenger train having a capacity of 300 passengers.

Similarly, for a cargo train called “Night Mail”, which contains the capacity of “1000” tons, the getDetails() method would return the following string:

Night Mail is a cargo train having a capacity of 1000 tons.

The skeleton code is already given to get you started.

Solution:

Q14. The Member class will have the following attributes:

  • amountOverdue: A OverdueFee type variable, containing information regarding the overdue fee.

The OverdueFee class will have the following attribute:

  • amount: A double type variable, containing the total amount a member owes to the library.
  • discountPercentage: A double type variable, containing the percentage that is applied to the amountDue and deducted from the total amount.

For this use case, the Member class object will compose an OverdueFee class object.

Member functions

You will need to implement the following methods for Member class:

  • setAmountOverdue(): This function takes two values as input, amount and discountPercentage (both are of double type). It then makes the necessary changes in the amountOverdue object.
  • getAmountOverdue(): This returns a double value equal to the amount after deducting the discount percentage. For example, if amount is 20 and discountPercentage is 10, then it should return 18.

Hint: The formula for above function is:

amount – [(discountPercentage/100) * amount].

In case the discountPercentage is zero, no amount should be deducted and implement error handling if needed.

Solution:
Conclusion:

I hope this Learn Object-Oriented Programming in Java Educative Quiz Answers would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions

Leave a Reply

Your email address will not be published. Required fields are marked *