Java Oops Ch1 Classobject

OOPS

Class

Class are the bluprint of the object.

Syntax:

class classname {
    type variable1;
    type variable2;
    type variable3; ...
    type function1(parameter-list){
    
        //body of the function1
    
    }
    type function2(parameter-list){
    
        //body of the function2
    
    
}

Example for class creation

class Rectangle
{
   double width;
   double height;
   
}

Object

Object is the instance of the class.

Example for the object creation

Rectangle rec = new Rectangle();

new operator

Important Definitions:

Example with 2 objects for a class.

class Rectangle
{
   double width;
   double height;
 }
 class Main
 {
 public static void main(String args[])
 {
   Rectangle rec1=new Rectangle();
   Rectangle rec2=new Rectangle();
   double vol;
   rec1.width=12;
   rec1.height=10;
    vol=rec1.width * rec1.height; 
   System.out.println("Rectangle 1 area:  "+vol);
   rec2.width=2;
   rec2.height=11;
    vol=rec2.width * rec2.height; 
   System.out.println("Rectangle 2 area:  "+vol);
   
 }
 }
 

### Result: Rectangle 1 area: 120.0
Rectangle 2 area: 22.0

Assigning object reference variables

Rectangle rec1=new Rectangle();
rec1=rec2;
type name(parameter-list){
//body of method

Example adding methods to Rectangle

class Rectangle
{
   double width;
   double height;
  double perimeter()
  {
    double p= 2*(width+height);
    return p;
  }
 }
 class Main
 {
 public static void main(String args[])
 {
   Rectangle rec1=new Rectangle();
   Rectangle rec2=new Rectangle();
   double vol;
   rec1.width=12;
   rec1.height=10;
    vol=rec1.width * rec1.height; 
   System.out.println("Rectangle 1 area:  "+vol);
   System.out.println("Rectangle 1 perimeter method:  "+rec1.perimeter());
   
   rec2.width=2;
   rec2.height=11;
    vol=rec2.width * rec2.height; 
   System.out.println("Rectangle 2 area:  "+vol);
   System.out.println("Rectangle 2 perimeter method:  "+rec2.perimeter());
     
 }
 }

Result:

Rectangle 1 area: 120.0
Rectangle 1 perimeter method: 44.0
Rectangle 2 area: 22.0
Rectangle 2 perimeter method: 26.0

Method that takes parameters

class Square
{
   double width;
   double area(double w)
  {
     width=w;
    double p= width*width;
    return p;
  }
 }
 class Main
 {
 public static void main(String args[])
 {
   Square s1=new Square();
     System.out.println("Square are: "+s1.area(10.0));
      
 }
 }
 

### Result Square are: 100.0