Java object and example

 

Java object and example

Definition of object:-

·      Object is an instance of a class.

·      Object is a real-world entity.

·      Objects occupy memory.

Objects consist of:-

Indent  --   name

State/attribute   -- color, bread, age

behavior -- run,  bark, eat

How to create an object:--

§  By using the new keyword

§  By using newInstance() method

§  By using the clone() method

§  By using deserialization

§  By using the factory() method

How to use a new keyword creating object?

Declaration:-  animal buzo it is declaring a variable name  with an object  type

Example:--  animal buzo;  (name of cat)where animal is class name and buzo reference variable name.

Working:--   animal buzo null memory null is assigned to the memory

Note:--    all the object Instance share the attribute and the behavior of the classes

                Simply declaring to reference variable does not create an object

Instance :---  buzo  =  new   buzo;

§  This is when memory is allocated for an object

§  The new keyword is used to create the object

§  A reference to the object that was created is returned from the new keyword

Initialization:--   the new keyword is followed by a call to a constructor this call initializes the new object.

For example:--   Buzo   =  new Animal ();

Working:--  in initialization the value is put into the memory that was allocated

Buzo= bread, age, color-(attributed)eat, run (behavior) all the state and behavior of and object is loaded in the memory

Example:--  Animal   buzo   =  new   Animal();

Syntax:--  buzo.eat();

Programming example:-

public class  Animal     {

public void eat()              {

System.out.println(“I am eating”);

}

public static void main (String   args[])   {

Animal   dog  =  new   Animal();

dog.eat()

}
}

How to object initialize:--

1.    By using reference

2.    By using the method

3.    By using   constructor

Example By using reference:--

public class  Animal     {

string  color;

int  age;

public static void main (String   args[])   {

Animal   dog  =  new   Animal();

dog.color = ”black”;

dog.age  = 12;

System.out.println(dog.color +“ ” + dog.age);

}
}

Example By using method:--

public class  Animal     {

string  color;

int  age;

void initobj(String  c,  int a)  {

color  =   c;

age  = a;

}

Void display() {

System.out.println(color +“ ” +age);

}

public static void main (String   args[])   {

Animal   dog  =  new   Animal();

dog.initobj = (”black”, 15)

dog.display()

}
}

Example By using constructor Example:--

 

public class  Animal     {

string  color = “blue”;

int  age =12;

void initobj(String  c,  int a)  {

color  =   c;

age  = a;

}

Void showData() {

System.out.println(color +“ ” +age);

}

public static void main (String   args[])   {

Animal   dog  =  new   Animal((”black”, 15);

dog.showData ()

}
}

 


Post a Comment

0 Comments