Showing posts with label OOP / Object Oriented Programming. Show all posts
Showing posts with label OOP / Object Oriented Programming. Show all posts

Wednesday, 25 January 2012

Access modifiers and non access modifiers meaning

http://way2java.com/oops-concepts/access-specifiers-access-modifiers/

Modifiers for variables, methods and classes

http://way2java.com/oops-concepts/access-modifiers-meanings/

Rules of Access Specifiers in Method Overriding

http://way2java.com/oops-concepts/rules-of-access-specifiers-in-method-overriding/

Modifiers and specifiers

http://way2java.com/oops-concepts/access-specifiers-access-modifiers/

OOPS concepts – Introduction

There are three basic concepts of OOPS

  1. Abstraction
  2. Encapsulation
  3. Polymorphism

1. Abstraction
Abstraction means using the equipment (or code) without knowing the details of working. For example, you are using your mobile phone without knowing how a mobile operates internally. Just a click on a button connects to your friend. This is abstraction. That is, the details of mobile mechanism are abstracted. Similarly we use the code of somebody to get the functionality without knowing how the code is written or working. For example, you are using printf() function to write to the DOS prompt without the awareness of what the code of printf(). One of the ways of achieving abstraction is inheritance. Through inheritance a subclass can use the super class methods as if they belong to it without caring their implementation details.
2. Encapsulation
Object-oriented concepts borrowed many terms from other technologies like encapsulation (from pharmaceuticals), inheritance (from biology), cloning (from genetics) and polymorphism (from biology) etc. Placing a powdered drug in a gelatin capsule and sealing it is known as encapsulation. With encapsulation, a Pharmacist hides the properties of a drug like its taste and color from the patient. Similar meaning is in OOPs also. Encapsulation hides the implementation details of coding; other way it is abstraction. With abstraction, implementation of information is hidden.
In a programming language, variables represent the properties and methods are used to change the properties. For example, the speed variable represent the property of a motor car and the method accelerator() is used to change the speed. Objects are used to call the methods. There may be multiple motor cars and every car has its own speed. Here, motor car represents an object. Every object encapsulates its own data. This encapsulation concept takes OOP languages a lead over traditional procedure-oriented languages. Binding data with objects (generally through method calls) is known as encapsulation.
In encapsulation, to have control over the manipulation of data (not to feed wrong data, for example, the speed cannot be negative) by other classes, a programmer declares variables as private and methods as public. Other classes can access the private variables through public methods. With encapsulation, every object maintains its own data and this data is entirely private to that object. Other objects cannot access or modify the data.
3. Polymorphism
Polymorphism is a Greek term and means many forms of the same ("poly" means many and "morphism" means forms). It is an OOP paradigm where one method can be made to give different outputs (functionalities) when called at different times. Polymorphism is two ways – static polymorphism where methods are binded at compile time and dynamic polymorphism where methods are binded dynamically at runtime. The same person is called as an officer (in office), husband (in house) and player (in cricket team). The person can be treated as base class. Extra subclasses can be added by hierarchical inheritance like son etc.

Types of inheritances in java

http://way2java.com/oops-concepts/types-of-inheritance/

Dynamic Polymorphism

http://way2java.com/oops-concepts/dynamic-polymorphism/

Method overloading

http://way2java.com/oops-concepts/using-methods-and-method-overloading/

Sunday, 15 May 2011

Explicit or direct Field Initialization in java

Because you can overload the constructor methods in a class, you can obviously build in many ways to set the initial state of the instance fields of your classes. It is always a good idea to make sure that, regardless of the constructor call, every instance field is set to something meaningful.
You can simply assign a value to any field in the class definition. For example,
class Employee

{

. . .

private String name = "";

}



This assignment is carried out before the constructor executes. This syntax is particularly useful if all constructors of a class need to set a particular instance field to the same value.

The initialization value doesn't have to be a constant value. Here is an example in which a field is initialized with a method call. Consider an Employee class where each employee has an id field. You can initialize it as follows:

class Employee

{

. . .

static int assignId()

{

int r = nextId;

nextId++;

return r;

}

. . .

private int id = assignId();

}



See cpp vs java in case of direct field initialization.

Difference between fields and local variables

There are few difference between fields and local variables. Fields are defined in the class, whereas local variables are local to the methods. The big difference comes in case of initialization.
You must always explicitly initialize local variables in a method. But if you don't initialize a field in a class, it is automatically initialized to a default (0, false, or null).

Explicit call to super class constructor in java

Normally, you don't explicitly write the constructor for your parent class, but there are two cases where this is necessary:

 

Passing parameters

You want to call a parent constructor which has parameters (the default construct has no parameters). For example, if you are defining a subclass of JFrame you might do the following.

class Chairman extends Employee {
. . .
//======== constructor
public Chairman(String name_,String designation_) {
super(name_);
This was shown here.

No parameterless constructor in parent


There is no parent constructor with no parameters. Sometimes is doesn't make sense to create an object without supplying parameters.

Referring to base class members using super in java

Referring to base class from derived class, can be done with the help of super. Here super acts somewhat like this, except that it always refers to the superclass of the subclass in which it is used. This usage has the following general form:

super.member


Here, member can be either a method or an instance variable.
class A {

int i;
}

// Create a subclass by extending class A.
class B extends A {
int i; // this i hides the i in A
B(int a, int b) {
super.i = a; // i in A
i = b; // i in B
}

void show() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}

}

Calling base class constructor using super in java

In java, we use super to call a constructor in a parent class. Calling the constructor for the superclass must be the first statement in the body of a constructor. If you are satisfied with the default constructor in the superclass, there is no need to make a call to it because it will be supplied automatically.

Usage

super(parameter-list);

Example

//X is super class, with attributes width, height, depth and has constructor for 3 attributes.

class Y extends X {
double weight; // weight of box // initialize width, height, and depth using super()

Y(double w, double h, double d, double m) {
super(w, h, d); // call superclass constructor
weight = m;
}
}

Calling another constructor in same class using this() in java

Often a constructor with few parameters will call a constructor with more parameters, giving default values for the missing parameters. Use this to call other constructors in the same class.

Eg.

public class Employee{
String name;
String designation;
public Employee(String name_){
name=name_;
}
public Employee(String name_,String designation_){
//here we are calling constructor with one parameter
//Suppose if we have lots of parameters, this does same some line of code
//and also gives clarity
this(name_);
designation = designation_;
}
}


This is also called local chaining of constructors. If we have lots of parameters, this helps us in making code clearer, also saving some effort of typing the line of codes, as we saw above.

Differences between methods and constructors.

  • There is no return type given in a constructor signature (header). The value is this object itself so there is no need to indicate a return value.
  • There is no return statement in the body of the constructor.
  • The first line of a constructor must either be a call on another constructor in the same class (using this), or a call on the superclass constructor (using super). If the first line is neither of these, the compiler automatically inserts a call to the parameterless super class constructor.
These differences in syntax between a constructor and method are sometimes hard to see when looking at the source. It would have been better to have had a keyword to clearly mark constructors as some languages do.

Thursday, 28 April 2011

SOLID - OOPS/OOAD Principle

The Object Oriented concepts in all OOPS language follow some common principles. These principles are guidelines for developers and architects which they need to understand as they grow their understanding of the language.

The SOLID principles are the most talked about in the Enterprise Java world. These principles deal with cohesion, coupling, inheritance, abstract types in the Object Oriented Analysis and Design (OOAD)

The five principles are also asked about in Java or JEE interview. SOLID is an acronym for 5 principles of the Java language which are listed here:

1) S - Single Responsibility Principle: This principle is very closely related to the highly cohesive design methodology. This principle says that each class, method and variable should have single responsibility to perform. If there are multiple responsibilities assigned to a class then it becomes very difficult to maintain as the Java application scales. So sufficient time should be given to think what responsibility will be assigned to which class, method or variable.

2) O - Open Closed Principle: This principle says that when a class is inherited by other class then the superclass should not be a candidate for change just because it is going to be inherited by some other class. Thus it can be said that a class may be open for inheritance but closed for change because of inheritance.

3) L - Liskov Substitution Principle: This principle says that when multiple classes inherit or implement a class/interface and we have reference of super type which references to an object of one of the sub type then changing the subtype object from one class to another should not make any change.
Vehicle v = new Suzuki();
v = new Benz();
The change of object in the above Java sample code should not make any change to the various methods being invoked other than the fact that the methods will now be invoked on Benz object instead of the Suzuki object.

4) I - Interface Segregation Principle: This principle says that instead of having a big fat interface or class, split the functionality into multiple parts.This is different from the Single Responsibility Principle because even if a class has a single responsibility, it can be split into multiple parts for better understanding and maintainability. One common method to split a fat class is to make it implement/inherit other thin interface/class.

5) D - Dependency Inversion Principle: This principle is very much similar to the Open Closed Principle it states that the super type should not be dependent on the sub type but the sub type should be dependent on the super type. The above is possible if abstract entities are super types and concrete types as sub types. The sub types can anytime changed without affecting the super types.

Here is the analysis for the above discussion:

S and I are similar but with the difference that I can be used when S makes a single class grow fat. I have seen some classes having 2000 lines of code and 10-15 methods. It really makes life Hell

O, L and D are similar but O to not changing the super type just because of inheritance relationship, L asks us to make sure that multiple sub type objects are substitutable for a reference of super type and D emphases on coding to interfaces or abstract classes

Friday, 22 April 2011

Casting Objects and instanceof

One of the difficulties of using a superclass array to hold many instances of subclass objects is that one can only access properties and methods that are in the superclass (ie. common to all). By casting an individual instance to its subclass form, one can refer to any property or method. But first take care to make sure the cast is valid by using the instanceof operator. Then perform the cast. As an example using the above Animal class:

if (ref[x] instanceof Dog) // ok right type of object
{
  Dog doggy = (Dog) ref[x]; // cast current instance to subclass
  doggy.someDogOnlyMethod();
}


Casts to subclass can be done implicitely but explicit casts are recommended. Casts to superclass must be done explicitly. Casts cannot be made between sibling classes.

Arrays of Base class objects

As with arrays of primitive types, arrays of objects allow much more efficient methods of access. Note in this example that once the array of Animals has been structured, it can be used to store objects of any subclass of Animal. By making the method speak() abstract, it can be defined for each subclass and any usage will be polymorphic (ie. adapted to the appropriate object type at runtime). It now becomes very easy to rehearse the speak() method for each object by object indexing.


public class AnimalArray
{
  public static void main(String args[])
  Animal ref[] = new Animal[3]; // assign space for array
  Cow aCow = new Cow("Bossy");  // makes specific objects
  Dog aDog = new Dog("Rover");
  Snake aSnake = new Snake("Earnie");

  // now put them in an array
  ref[0] = aCow; ref[1] = aDog; ref[2] = aSnake;

  // now demo dynamic method binding
  for (int x=0;x<3;++x) { ref[x].speak(); }
}

Polymorphism

Polymorphism is the capability of an action or method to do different things based on the object that it is acting upon. This is the third basic principle of object oriented programming. Overloading, overriding and dynamic method binding are three types of polymorphism.
Overloaded methods are methods with the same name signature but either a different number of parameters or different types in the parameter list. For example 'spinning' a number may mean increase it, 'spinning' an image may mean rotate it by 90 degrees. By defining a method for handling each type of parameter you control the desired effect.
Overridden methods are methods that are redefined within an inherited or subclass. They have the same signature and the subclass definition is used.
Dynamic (or late) method binding is the ability of a program to resolve references to subclass methods at runtime. As an example assume that three subclasses (Cow, Dog and Snake) have been created based on the Animal abstract class, each having their own speak() method. Although each method reference is to an Animal (but no animal objects exist), the program is will resolve the correct method reference at runtime.

public class AnimalReference
{
  public static void main(String args[])
  Animal ref                 // set up var for an Animal
  Cow aCow = new Cow("Bossy"); // makes specific objects
  Dog aDog = new Dog("Rover");
  Snake aSnake = new Snake("Ernie");

  // now reference each as an Animal
  ref = aCow; ref.speak();
  ref = aDog; ref.speak();
  ref = aSnake; ref.speak();
}

Object Creation and Destruction

To create an object of a particular class use the new operator. For example, now that there is a constructor for the Box class you can make specific instances or discrete copies of a box by using the assignment operator and the new memory allocation operator as in:
Box box_1=new Box(3,4,5);
Note: Once a class has been specified, a datatype exists with the same name.
You do not need to destroy or remove an object when it is no longer needed. Java automatically flags unused objects and applies garbage collection when appropriate. However you may occasionally need to use the finalize() method to insure that a non-Java resource such as a file handle or a window font character is released first. The general form is:
void finalize()
{
//cleanup code goes here
super.finalize() //parent too!
}