Classes and Objects
Classes and Objects
Definition of Class:
Class defines a new data type. Once defined, this new type can be used to create objects of that type. Thus, a class is a template for an object, and an object is an instance of a class. In other words, class is a collection of fields (instance and class variables) and methods.
The data, or variables, defined within a class are called instance variables. The code is contained within methods. Collectively, the methods and variables defined within a class are called members of the class. Detail about An instance variable is a variable that is defined in a class, but outside of a method. There is one copy of the variable for every instance (object) created from that class.
A common problem is trying to reference an instance variable from a static method. A static method (eg, main) can only reference static variables in its own class (or its own local variables). Creating object of the class A class is merely a plan for a possible object. It does not by itself create any objects. When a programmer wants to create an object the new operator is used with the name of the class. Creating an object is called instantiation. Object Declaration : An object is declared using a variable name(object name) and type of the objects. Mainclass mc; Object Instantiation : The 'new ' key word is used to create the object. mc = new Mainclass(); Object Initialization (Optional step): The 'new' keyword is followed by a call to a constructor. This call initializes the new object. mc = new Mainclass("Ankit");