Class and Object - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript Class and Object - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Thursday, March 14, 2019

Class and Object

Class and Object


üA class defines a new data type. This new data type is used to 
create objects of that type.
üA class is a template for an object and an object is an instance 
of a class.

Creating Objects


üObtaining objects of a class is two steps process:


  1. Declare a variable of the class type.

  2. Acquire an actual, physical copy of the object and assign it to that variable.

ü To allocate a physical memory new() is used. It 
dynamically allocates memory for an object and returns a 
reference to it.

üIn Java, all class objects must be dynamically allocated.

A Simple Example

class Box

{

  double width;

  double height;

  double depth;

}
class BoxDemo

{

  public static void main( String args[])

  {

  Box mybox, mybox1;

  mybox = new Box();

  mybox1 = new Box();

  mybox.width=10;

  mybox.height = 20;

  mybox. depth = 15;

  mybox1.width = 10;

  mybox1.height = 25;

  mybox1.depth=5;

  }

}

A Simple Example- Some points

üMembers are linked to an object using dot (.) operator.

üEach object contains its own copy of each instance 
variables defined by the class.

üThe java compiler automatically puts each class into its own .class file.

  - For this example, two .class files:

  1. Box.class

    2. BoxDemo.class

new() is used to dynamically allocate memory for an object.

No comments:

Post a Comment

Post Top Ad