Monday, 22 February 2016

Java and its Features in brief

What is Java?

Java is a Object Oriented Programming Language.
Main Features of Java are :
Class :- Template
Object :- Instance with Specific Values
Inheritance :- Creating new classes by extending the features of existing classes
Polymorphism :- A single variable of class type can take multiple forms i.e. a variable can be assigned to objects of different types along the class hierarchy

Class :

Definition of class
class <name>

class X{
int x;
X(int x) { this.x = x; } 
int getX() { //body }
void setX(int x) { //body}

Object :

Using keyword new we create an instance i.e. object of a class.
X temp = new X(5);

Inheritance :

Another class  Y
Class Y extends X{
int y;
Y(int x,int y) { super(x); this.y = y; } 
int getY() { //body }
void setY(int y) { //body}

Here the method getX() and setX(int x) are inherited in class Y and can be called from class Y.

Polymorphism :

Another class Z instatiates X and Y classes.
class Z{
int z;
X temp = new X(5);
System.out.println("X : " + temp.getX());
temp = new Y(5,10);
System.out.println("X : " + temp.getX()); // cannot call temp.getY() as temp is variable of type X which does
                                                              // not have method getY()
Same variable can take multiple forms i.e. it can be assigned an instance of X or Y. Hence same variable temp takes multiple forms.
This is polymorphism.

No comments:

Post a Comment