Wednesday, 25 January 2012
Access modifiers and non access modifiers meaning
Modifiers for variables, methods and classes
Rules of Access Specifiers in Method Overriding
OOPS concepts – Introduction
- Abstraction
- Encapsulation
- 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.
Sunday, 15 May 2011
Explicit or direct Field Initialization in java
class Employee
{
. . .
private String name = "";
}
class Employee
{
. . .
static int assignId()
{
int r = nextId;
nextId++;
return r;
}
. . .
private int id = assignId();
}
Difference between fields and local variables
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 {This was shown here.
. . .
//======== constructor
public Chairman(String name_,String designation_) {
super(name_);
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 (usingsuper). If the first line is neither of these, the compiler automatically inserts a call to the parameterless super class constructor.
Thursday, 28 April 2011
SOLID - OOPS/OOAD Principle
Friday, 22 April 2011
Casting Objects and instanceof
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
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
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
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!
}