You are on page 1of 2

CODE:

class TestMultipleConstructors
{
    public static void main(String arg[])
    {
                Student yogesh = new Student("Yogesh", 67, 'B');
                Student narayan = new Student("Narayan", 72);
                Student mahesh = new Student("Mahesh");
                
                System.out.println(yogesh.name + " belongs to section " + yogesh.section + " and got " +
yogesh.marks + " marks.");
                System.out.println(narayan.name + " belongs to section " + narayan.section + " and got " +
narayan.marks + " marks.");
                System.out.println(mahesh.name + " belongs to section " + mahesh.section + " and got " +
mahesh.marks + " marks.");
    
    }
}

class Student
{
    String name;
    int marks;
    char section;
    
    // CONSTRUCTOR 1
    Student(String nameParam, int marksParam, char sectionParam)
    {
        name = nameParam;
        marks = marksParam;
        section = sectionParam;
    }

    // CONSTRUCTOR 2
    Student(String nameParam, int marksParam)
    {
        name = nameParam;
        marks = marksParam;
        section = 'A';
    }
    
    // CONSTRUCTOR 3
    Student(String nameParam)
    {
        name = nameParam;
        marks = 0;
        section = 'A';
    }
    
}

OUTPUT

Yogesh belongs to section B and got 67 marks.


Narayan belongs to section A and got 72 marks.
Mahesh belongs to section A and got 0 marks
Description:

Here we have defined 3 constructors - CONSTRUCTOR


1 takes nameParam, marksParam and sectionParam as inputs, CONSTRUCTOR
2 takes nameParam and marksParam where as CONSTRUCTOR 3 takes
only nameParam. Also note that CONSTRUCTOR
2 defaults section to 'A' and CONSTRUCTOR
3 defaults marks to 0 and section to 'A'. In the main class we have created
students yogesh, narayan and mahesh using the three constructors and printed the
student details. For printing the variables we have used the dot ( .) operator.

You might also like