Menu
Topics Index
...
`


Classes >
Siva Nookala - 12 Apr 2016
As explained in Java Class, classes can be used to group related data. Methods using this data can be defined in the class.

If we have a Student class as shown below.
class Student
{
    String name;
    int marks;
    char section;

    Student(String name, int marks, char section)
    {
        this.name = name;
        this.marks = marks;
        this.section = section;
    }
}
We can create multiple student object and print the details as shown below.
Student yogesh = new Student("Yogesh", 85, 'B');
Student narayan = new Student("Narayan", 72, 'A');
Student mahesh = new Student("Mahesh", 98, 'C');
                
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.");
Alternatively we can add print method the Student class and use it for printing. The methods created in the class are similar to the methods we discussed in Java Methods. Every method will have a name, method parameters and a return type.
The print method can be defined as shown below
class Student
{
    String name;
    int marks;
    char section;

    Student(String name, int marks, char section)
    {
        this.name = name;
        this.marks = marks;
        this.section = section;
    }

    // PRINT METHOD
    void print()
    {
        System.out.println(name + " belongs to section " + section + " and got " + marks + " marks.");
    }
}
We can call the newly created method using the dot(.) operator on the objects.
Student yogesh = new Student("Yogesh", 85, 'B');
Student narayan = new Student("Narayan", 72, 'A');
Student mahesh = new Student("Mahesh", 98, 'C');
                
yogesh.print();
narayan.print();
mahesh.print();

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.