Syed Imran Murtaza

Software Engineer

Front-end Developer




No products in the cart.

Syed Imran Murtaza
Syed Imran Murtaza
Syed Imran Murtaza
Syed Imran Murtaza
Syed Imran Murtaza
Syed Imran Murtaza

Software Engineer

Front-end Developer



Blog Post

Java OOP Project

June 22, 2024 Blog
Java OOP Project

Overview: The Online Quiz System is a Java application designed to facilitate quizzes of varying difficulty levels (easy, medium, hard) for users. It utilizes object-oriented programming principles such as inheritance, abstraction, and encapsulation to manage quiz questions, user interaction, scoring, and grading.

Four Pillars in OOP:
In the Java code for the Online Quiz System, we’re using four main ideas from Object-Oriented Programming (OOP):

  1. Abstraction:
    What it does: It helps us create a blueprint for questions in the Question class. This blueprint includes basic details like the question text and marks.
    Why it’s useful: It allows us to define how different types of questions should work without worrying about all the specific details of each question.
  2. Inheritance:
    What it does: It lets one class (MultipleChoiceQuestion) extend another class (Question). This means MultipleChoiceQuestion gets all the attributes and methods from Question.
    Why it’s useful: It helps us reuse code and organize it better. For example, all types of questions share common behaviors defined in Question.
  3. Encapsulation:
    What it does: Encapsulation means bundling data (like question text) and methods (like checkAnswer()) together inside a class (Question, MultipleChoiceQuestion, etc.).
    Why it’s useful: It keeps the inner workings of each class private and controlled. This protects data from being changed unexpectedly and allows us to manage how data is accessed.
  4. Polymorphism:
    What it does: It allows us to treat objects of different classes (Question, MultipleChoiceQuestion) in a unified way in the Quiz class.
    -Why it’s useful: It lets us work with different types of questions using a single interface (Question). This flexibility makes the code more adaptable to changes and additions in the future.

These concepts make the Online Quiz System easier to understand, modify, and expand. They help organize the code logically and make it more flexible for handling different types of quiz questions and interactions with users.

Source Code:

package onlinequiz;

import java.util.Scanner;

//Encapsulation and Abstraction:
abstract class Question { //Class#01 //Abtsract Class
protected String questionText;
protected int marks;

public Question(String questionText, int marks) {    //arg-constructor
    this.questionText = questionText;
    this.marks = marks;

public abstract boolean checkAnswer(String userAnswer);  // Abstract method


//Concrete subclass of Question

class MultipleChoiceQuestion extends Question { //Class#02
private String[] options;
private int correctOption;

// Constructor for MultipleChoiceQuestion
public MultipleChoiceQuestion(String questionText, int marks, String[] options, int correctOption) {

    super(questionText, marks);    //constructor of the superclass (parent class)
    this.options = options;
    this.correctOption = correctOption - 1; // Adjust to 0-based index

public String[] getOptions() {
    return options;

// Polymorphism:
public boolean checkAnswer(String userAnswer) {
if (userAnswer == null || userAnswer.isEmpty()) {
return false;

    boolean isInteger = true;
    for (int i = 0; i < userAnswer.length(); i++) {
        if (!Character.isDigit(userAnswer.charAt(i))) {
            isInteger = false;

    if (isInteger) {
        int userOption = Integer.parseInt(userAnswer) - 1; // Adjust to 0-based index
        return userOption == correctOption;
    } else {
        return false;


//Encapsulation, Inheritance, Abstraction:
class Quiz { //Class#03
private Question[] questions;
private int score;
private int totalMarks;
private String userName;
private String userClass;
private long startTime;
private long endTime;

public Quiz(Question[] questions, String userName, String userClass) {
    this.questions = questions;
    this.score = 0;
    this.totalMarks = 0;
    this.userName = userName;
    this.userClass = userClass;
    for (Question q : questions) {
        this.totalMarks += q.marks;

// Encapsulation, Abstraction:
public void start() {
    Scanner scanner = new Scanner(;

    System.out.println("Welcome, " + userName + "!");
    System.out.println("You are in class " + userClass);
    System.out.println("1. You will get " + totalMarks + " marks for this quiz.");
    System.out.println("2. Each correct answer will earn you marks based on the question.");
    System.out.println("3. There are no negative marks for wrong answers.");
    System.out.println("4. Type the number corresponding to your answer and press Enter.");
    System.out.println("Press Enter to start the quiz...");

    startTime = System.currentTimeMillis();   //captures the current time in milliseconds

    for (Question question : questions) {

        if (question instanceof MultipleChoiceQuestion) {
            MultipleChoiceQuestion mcq = (MultipleChoiceQuestion) question;
            for (int i = 0; i < mcq.getOptions().length; i++) {
                System.out.println((i + 1) + ". " + mcq.getOptions()[i]);

        String userAnswer = scanner.nextLine();

        if (question.checkAnswer(userAnswer)) {
            score += question.marks;

    endTime = System.currentTimeMillis();

// Encapsulation:
static class Grading {                                                     //Class# 04
    public static String calculateGrade(int score, int totalMarks) {
        double percentage = (double) score / totalMarks * 100;
        if (percentage >= 90) {
            return "A";
        } else if (percentage >= 80) {
            return "B";
        } else if (percentage >= 70) {
            return "C";
        } else if (percentage >= 60) {
            return "D";
        } else {
            return "F";

// Encapsulation, Abstraction:
public void showResult() {
long durationSeconds = (endTime – startTime) / 1000;
System.out.println(“Quiz ended. Your score: ” + score + “/” + totalMarks);
System.out.println(“Grade: ” + Grading.calculateGrade(score, totalMarks));
System.out.println(“Time taken: ” + durationSeconds + ” seconds”);

//Encapsulation, Abstraction:
class ChooseLevels { //Class# 05
public void Levels(String level, String name, String className) {
Question[] questions;

    switch (level.toLowerCase()) {
    case "easy":
        questions = new Question[]{
                new MultipleChoiceQuestion("Who is Mickey Mouse's Sister?", 2, new String[]{"Minnie Mouse", "Daisy Duck", "Donald Duck", "Goofy"}, 1),
                new MultipleChoiceQuestion("Which planet is closest to the Sun?", 2, new String[]{"Venus", "Mars", "Mercury", "Earth"}, 2),
                new MultipleChoiceQuestion("What is the largest ocean on Earth?", 2, new String[]{"Atlantic Ocean", "Indian Ocean", "Arctic Ocean", "Pacific Ocean"}, 4),
                new MultipleChoiceQuestion("What do caterpillars turn into?", 2, new String[]{"Butterflies", "Moths", "Dragonflies", "Bees"}, 1),
                new MultipleChoiceQuestion("How many continents are there on Earth?", 2, new String[]{"6", "7", "5", "8"}, 2)
    case "medium":
        questions = new Question[]{
                new MultipleChoiceQuestion("Who painted the Mona Lisa?", 2, new String[]{"Leonardo da Vinci", "Michelangelo", "Vincent van Gogh", "Pablo Picasso"}, 1),
                new MultipleChoiceQuestion("What is the largest planet in our solar system?", 2, new String[]{"Mars", "Jupiter", "Saturn", "Uranus"}, 2),
                new MultipleChoiceQuestion("Which famous scientist developed the theory of relativity?", 2, new String[]{"Isaac Newton", "Albert Einstein", "Galileo Galilei", "Stephen Hawking"}, 2),
                new MultipleChoiceQuestion("What is the main component of Earth's atmosphere?", 2, new String[]{"Oxygen", "Nitrogen", "Carbon Dioxide", "Helium"}, 2),
                new MultipleChoiceQuestion("What year did the Titanic sink?", 2, new String[]{"1910", "1912", "1914", "1916"}, 2)
    case "hard":
        questions = new Question[]{
                new MultipleChoiceQuestion("Which chemical element has the symbol 'Sn'?", 2, new String[]{"Tin", "Titanium", "Tungsten", "Thallium"}, 1),
                new MultipleChoiceQuestion("Who wrote the novel 'War and Peace'?", 2, new String[]{"Leo Tolstoy", "Fyodor Dostoevsky", "Anton Chekhov", "Ivan Turgenev"}, 1),
                new MultipleChoiceQuestion("What is the only planet in our solar system known to support life?", 2, new String[]{"Mars", "Earth", "Venus", "Jupiter"}, 2),
                new MultipleChoiceQuestion("Who painted the famous painting 'The Scream'?", 2, new String[]{"Edvard Munch", "Vincent van Gogh", "Pablo Picasso", "Claude Monet"}, 1),
                new MultipleChoiceQuestion("In what year did World War II end?", 2, new String[]{"1943", "1945", "1947", "1950"}, 2)
        questions = new Question[0];

    Quiz quiz = new Quiz(questions, name, className);


//Main class
public class OnlineQuizSystem { //Class06
public static void main(String[] args) { //Object
Scanner scanner = new Scanner(;
System.out.print(“Enter your name: “);
String name = scanner.nextLine();
System.out.print(“Enter your class: “);
String className = scanner.nextLine();
System.out.print(“Enter the level of difficulty (easy, medium, hard): “);
String level = scanner.nextLine();

    ChooseLevels chooseLevels = new ChooseLevels();
    chooseLevels.Levels(level, name, className);


Structure and Explanation of the code for the Online Quiz System:

  1. Main Program (OnlineQuizSystem)
    Purpose: This is the starting point of our program. It interacts with the user to gather their name, class, and the difficulty level of the quiz they want to take (easy, medium, or hard).

It asks the user for their name and class.
It prompts the user to choose a difficulty level for the quiz.
Based on the user’s inputs, it creates an instance of ChooseLevels and starts the quiz.

  1. Quiz Levels (ChooseLevels)
    Purpose: This class handles the different difficulty levels (easy, medium, hard) of the quiz.

It takes inputs for the quiz level, user name, and class.
Depending on the chosen level (easy, medium, hard), it prepares a set of questions.
It creates a Quiz object with these questions and starts the quiz.

  1. Quiz (Quiz)
    Purpose: This class manages the entire quiz process, including presenting questions, collecting user answers, calculating scores, and displaying results.

questions: An array holding all the questions for the quiz.
score: Keeps track of the user’s total score during the quiz.
totalMarks: Sum of all available marks in the quiz.
userName, userClass: Stores the user’s name and class for personalization.
startTime, endTime: Records the starting and ending times of the quiz for time calculation.

start(): Initiates the quiz by displaying rules and instructions. It then iterates through each question, presents it to the user, collects their answer, and calculates scores based on correctness.
showResult(): Displays the user’s final score, calculates their grade based on the percentage of correct answers, and shows the time taken to complete the quiz.

  1. Question Classes (Question and MultipleChoiceQuestion)
    Purpose: These classes define the structure and behavior of different types of quiz questions.

Question(Abstract Class): Defines common attributes (questionText,marks) and a method (checkAnswer()`) that all question types should implement.

MultipleChoiceQuestion(Subclass ofQuestion): SpecializesQuestionfor multiple-choice questions. Adds attributes (options,correctOption) and overridescheckAnswer()` to validate user responses against the correct option.

  1. Grading (Grading)
    Purpose: Nested static class within Quiz that calculates the grade based on the user’s score compared to the total marks.

calculateGrade(int score, int totalMarks): Computes the grade (A, B, C, D, F) based on the percentage of correct answers.

Purpose and Scope
Purpose: Clearly state the objective of the Online Quiz System, which is to facilitate interactive quizzes with varying difficulty levels for users.
Scope: Define the boundaries of the system, including its intended users (students, learners, etc.), functionality (quiz initiation, question presentation, scoring), and limitations (e.g., only text-based interface).

The structure of the Online Quiz System uses classes and methods to organize different aspects of the quiz-taking process. It starts from gathering user information and level selection, proceeds through managing the quiz itself with various types of questions, and concludes by evaluating the user’s performance and displaying results. This organization makes the code clear, modular, and easy to expand for future enhancements.

Happy Ending (!!!!!

Write a comment