Tuesday 21 August 2018

Class/Objects and Methods


 Defining a Class and Object:
Class: class is a user defined data type that represents an entity, which is a collection of members and methods.
The entire set of data and code of an object can be made the user define data type with help of a class. Infact objects are variables of type class. Once a class has been defined, we can create any number of objects belonging to that class.
Syntax:            class class_name
                        {
                                    variable declarations/data members;
                                    function declarations/member functions;
}
The class body contains the declarations of variables and functions, which are called as class members. The variables declare inside the class are known as data members and functions are known as member functions.

Creating Objects

Object: is a functionable element that is used to access the members and methods of a class. Simply, object is an instance of class.
The declaration of an object is similar to that of a variable of any basic type.
Syntax: classname obj_name=new classname();
Example: student s=new student();
where s is an object of class student.

Accessing class members

Once an object of a class has been created there must be a provision to access its members. This is done by using the member access operator (.) called as dot.
Syntax:
            Object_name.datamember=value;
            Object_name.memberfunction(actual_args);

Example:
            s.a=10;
            s.display();

Example program:
class student   //userdefined class
{         
int sno=10;       //members/fields declaration   
void show()     //method declaration   
{                     
System.out.println("Hai");       
}
}
class simple    
{
            public static void main(String []args)
            {
                        student s=new student(); //object created
                        System.out.println("Sno="+s.sno);  //accessing members of class
                        s.show();          //calling method
            }
}
Output:C:\>javac simple.java

C:\>java simple

Sno=10

Hai


No comments: