Saturday, July 11, 2015

Student class with overloaded constructors and method to display object


class Student{
    String name;
    int roll;
    int marks;
    Student(){            // default constructor
        name="unnamed";
        roll=0;
        marks=0;
    }
    Student(String s, int r, int m){    // overloaded constructor with 3 arguments
        this.name=s;
        this.roll=r;
        this.marks=m;
    }    
    void display(){            //method to display the object
        System.out.println("Student Details:");
        System.out.println("Name:"+this.name+" Roll:"+this.roll+" Marks"+this.marks);
    }
}
class TestStudent{            //class to test the Student class
    public static void main(String args[]){            //main method
        Student s1=new Student();
        Student s2=new Student("abcd",12, 80);
        s1.display();
        s2.display();
    }
}
Compile:
javac TestStudent.java

Run
java TestStudent

No comments:

Post a Comment