Dec 15, 2008

Basics of Java

Complexity can be handled by abstraction. In OOPS abstraction is modeled using Classes and objects.
A Class models abstraction by defining properties and behavior of an object.
Properties of an object are defined by the attributes, which are fields in java. A field in java is a variable that can hold value.
Behavior of an object is defined by the methods in java.

Object is an instance of the class. In java objects can only be manipulated using references.
Each Object created maintains its own copy of instance variables. Two objects can have same state if the values of their instance variable are same.
Object communicates with each other using message passing.

Static members/methods
  1. Certain members belong to Class only not to object these are called static members.
  2. A static member is initialized when the class is loaded at runtime.
  3. Certain methods that belong to the Class only and not to an object are called static methods.
  4. Client can access static methods using the class name.
  5. Static members of the Class can be accessed either using Object reference or using Class name.
Example of Class & Object
package Test;
//Class declaration
public class Example_Class {
//Attribute declaration - These variables defines the state of the object
private int first_attribute;
private int second_attribute;
//constructor
public Example_Class(int x, int y) {
//Initializing attributes of newly created object.
this.first_attribute = x;
this.second_attribute =y;
}
//Method - These methods define the behavior of the object
public int addResult() {
return first_attribute + second_attribute;
}
//Main method of Class
public static void main(String[] args) {
/* Object instantiation - Object is created using "new" keyword With new keyword Constructor of the class is called which returns the reference of the newly created object, which is assigned to
reference variable of appropriate Class.
*/
// objFirst ---------> Object1(1,2)
Example_Class objFirst = new Example_Class(1, 2);
//Both objFirst and objSecond object refernces will point to two different objects in heap
// objSecond ---------> Object2(1,2)

Example_Class objSecond = new Example_Class(1, 2);
int addResultFirst = objFirst.addResult();
System.out.println("Add Result First:" + addResultFirst);
//Calling method on second created Object
int addResultSecond = objSecond.addResult();
System.out.println("Add Result Second:" + addResultSecond);
}
}

No comments:

Post a Comment