Object-Oriented Programming

This is a cheatsheet to brush up before attending interview.

Object: State+ Behavior.

Let’s take an example of real world object.  I see a Table Fan  infront of me 🙂

It has a state: On or Off, currentSpeed, Timer

These states can be changed through behaviors like turnOn, turnOff etc.

Software object also has state stored in “field” and behavior exposed using “methods”.

Data Encapsulation: The internal state of the objects are hidden. Methods are the only communication medium to interact with the state of an object.

Information hiding: The internal implementation details of an object remain hidden from outside world due to interactions enabled through object methods.

Class: It’s a blueprint from which objects are created.

In real world we see many objects being similar. They may share same blueprint.


Class TableFan{
   String state = "Off";
   int speed =0;
   static final MAX_SPEED=4;

   void turnOn(){
     state = "On";
   }

   void turnOff(){
     state = "Off";
   }

   void increaseSpeed(){
      if(speed<MAX_SPEED){
         speed = speed+1;
   }

   void decreaseSpeed(){
      if(speed>0)
         speed = speed-1;
   }

}

Inheritance: Different objects have certain amount of similar capabilities. OO-programming allows classes to inherit and refine common state and behavior from other classes. Java supports each class to have one direct superclass and a class can have multiple subclass.

Eg:


Class Circle extends Shape{
// Inherits from Shape class.
// Modify Shape class methods if necessary.
// Adds fields/methods particular to Circle class
}
Advertisements