Showing posts with label Class and Object in Java. Show all posts
Showing posts with label Class and Object in Java. Show all posts

Class and Object in Java

What is a Class in Java

Class and Object in Java

A class is a blueprint that defines the variables and methods common to all objects of a certain kind.

Example: „your dog‟ is a object of the class Animal.
  • An object holds values for the variables defines in the class.
  • An object is called an instance of the Class
  • A basis for the Java language.
  • Each concept we wish to describe in Java must be included inside a class.
  • A class defines a new data type, whose values are objects:
  • A class is a template for objects
  • An object is an instance of a class

Class Definition

class contains a name, several variable declarations (instance variables) and several method declarations. All are called members of the class.



General form of a class:


class classname 
                         {
                                  type instance-variable-1;
                                   …
                                 type instance-variable-n;
                                 type method-name-1(parameter-list) { … }
                                 type method-name-2(parameter-list) { … }
                                  …
                                  type method-name-m(parameter-list) { … }
                           }


Object

Real world objects are things that have:
  1.  state
  2.  behavior
Example: your dog:
state –name, color, breed, sits?, barks?, wages tail?, runs?
behavior –sitting, barking, waging tail, running
A software object is a bundle of variables (state) and methods (operations).

Object Creation:

A variable is declared to refer to the objects of type/class String:
String s;
The value of s is null; it does not yet refer to any object.
A new String object is created in memory with initial “abc” value:
String s = new String(“abc”);
Now s contains the address of this new object.

Example: Class Usage

class Box
{
double width;
double height;
double depth;
}
class BoxDemo
{
public static void main(String args[])
{
Box mybox = new Box();
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
vol = mybox.width * mybox.height * mybox.depth;
System.out.println ("Volume is " + vol);
}
}

Example for class

class sum
{
int a,b,sum; 
void get()
{
a=10;b=5;
}
void sum()
{
sum=a+b;
//System.out.print("sum is "+sum);
}
}
class sum1
{
public static void main(String args[])
{
sum s1=new sum();
s1.get();
s1.sum();
System.out.print("sum is" +s1.sum);
}