Topics Index

Classes >
Siva Nookala - 14 Mar 2016
A class comprises of various variables (or attributes). For e.g., the Student class is comprised of variables name, marks and section, the Car class is comprised of variables owner, registrationNumber, engineCC etc., These class variables are also called as instance variables or member variables or class attributes.

class Student
    String name;
    int marks;
    char section;
    String address;
    long mobile;
The variables of the class can be used to using the dot (.) operator. The variables in the student class can be accessed as shown below.
Student mahesh = new Student(); // LINE A = "Mahesh Babu";
mahesh.marks = 87;
mahesh.section = 'A';

System.out.println( + " belongs to section " + mahesh.section + " and he got " + mahesh.marks + " marks.");
Here mahesh is the reference pointing to the Student object created in LINE A Access-member-variables Another Student ntr can be created and the variables in it can be accessed similarly.
Student ntr = new Student(); // LINE B = "N T Rama Rao";
ntr.marks = 85;
ntr.section = 'A';

System.out.println( + " belongs to section " + ntr.section + " and he got " + ntr.marks + " marks.");
As discussed in the Java Objects References, there are now two references mahesh and ntr, pointing to two objects created at LINE A and LINE B respectively.
Also note that when we try to access the variables using a reference which does not point to any object, we get a NullPointerException during run-time.
Student prabhas = null; // LINE B = "Prabhas"; // Throws NullPointerException

Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App