Menu
Topics Index
...
`

Multiple Constructors for Student - Java Example Program


Multiple Constructors for Student
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.

THINGS TO TRY
  • Create one more student Srinath with 85 marks and in section 'C' and print his details.
  • Change the marks of mahesh to 90 and his section to 'D' and print his details. Use the dot(.) operator to access the variables.

© meritcampus 2019

All Rights Reserved.

Open In App