December 17, 2017

Classes and Objects

Here in this chapter, we will look into the concepts of Classes and Objects.

Class:
  • Class is used to create our own data type
  • Class is a blue print which has only template
  • Class will describe the behavior and state of the objects
  • Class is a logical entity which will occupy any space in the memory
Syntax:
Class <className>
{
<datatype 1 > <variable 1>;
<datatype 2 > <variable 2>;
<datatype 3 > <variable 3>;

void method1(){}
void method2(){}
}
In the above syntax, variables/fields represent the states and methods represents the behavior

Ex:
Class Phone
{
int memory;
String manufacturer;
double screenSize;

void call(){}
void message(){}
}

In the above example Phone is a User defined data type. Memory, manufacturer and screenSize are the fields which represents the state of the Phone. Call and message are the two features of the phone which represents the behavior of the phone.
Objects:
  • Objects have the states and behavior
  • Objects will be created the class and the
  • Objects will have state and behavior
  • As the Objects are physical entities they will stored in the memory
How to create the Objects?
Syntax:
<Class Name> <variable Name> = new <Class Name>();
In the above Syntax, we have 3 steps
1.        Declaration - <Class Name> <variable Name>
2.       Instantiation – new keyword is used to create the objects
3.       Initialization – new keyword followed by <class name>()
Ex:
                Phone lPhone =new Phone();

The following program shows the implementation of CLASS & OBJECTS

Class Phone
{
// Fields/Class Variables Declaration
                int memory; //1,2,3,4
                String Manfacturer; //"Sansung", "Sony", "Apple", "Windows"
                float dimention; //5,5.5,4.5
               
// Behavior/Methods Declaration
                void call()
                {
                }
                void message()
                {
                }
               
                void tuggleWifi()
                {
                }

Public static void main(String args[])
{
// Object Creation
Phone IPhone=new Phone();
}
}

0 comments:

Post a Comment