Tuesday, December 7, 2010

Accessing class members

Accessing class members:
class members are accessed within the class.
class members are accessed through class member function.
instance of a class is needed to access class public/private members, outside of its class scope.


Note: private members of a class cannot able to access outside of the class scope. To know more refer access specifiers.


syntax for accessing class members through object:


a dot operator(.) is used to access the class members through instance of a class.

object_name.member_of_a_class;


Example:
S.name='Raja';
here 'S' is object for the class Student and 'name' is instance variable of that class.

Here is a small example to demonstrate accessing class members.

class Student
{
char name[30];
void get_details;
void display_details;
private:
int reg_no;
protected:
char address[40];
}
class Student_details extends Student //inheritance
{
 address="Saveetha Engg College, Chennai.";//derived can access the protected member of a class.*/
reg_no=1042;/*generates error, because scope of the private member is within the class. Not outside of a class or derived class*/
}
class Main
{
public static void main(String args[])
{
Student S=new Student();
S.get_detials();
S.display_details();
S.name="Ragu";
S.reg_no;/*this line generates error. Because we are allowed to access protected member only inside the scope and derived class*/
S.address;/*this line also generates error. Because we are allowed to access protected member only inside the scope*/
}
}

No comments:

Post a Comment