Tuesday, August 18, 2015

Static and Dynamic Binding

class A{
int i= 10;
void m1(){
System.out.println("This is A");
}
}

class B extends A{
int i = 12;
void m1(){
System.out.println("This is B");
}
}

class Demo{
public static void main(String[] args){
A a1 = new B();
System.out.println(a1.i);
a1.m1();
}
}



Output:
------------------
10
This is B



Summary:
------------------
Variable binding is static in java
Method binding is dynamic in java

Fan class

class Fan{
public final static int SLOW = 11;
public final static int MEDIUM = 12;
public final static int FAST = 13;

int speed=Fan.SLOW;
boolean fOn = false;
int radius = 4;
String color = "blue";

Fan(){

}


Fan(int speed, boolean status, int radius, String color){
this.speed= speed;
this.fOn = status;
this.radius = radius;
this.color= color;
}


void display(){
if(this.fOn==true){
System.out.println("\n\nSpeed is "+this.speed);
System.out.println("Color is "+this.color);
System.out.println("Radius is "+this.radius);


}else{
System.out.println("\n\nColor is "+this.color);
System.out.println("Radius is "+this.radius);
System.out.println("Fan is Off");

}

}

}

class TestFan{
public static void main(String[] args){
Fan f1 = new Fan();
Fan f2 = new Fan(Fan.MEDIUM, true, 6, "Brown");


f1.display();
f2.display();


}
}

Vegetable Class

abstract class Vegetable{
String color;
}
class Potato extends Vegetable{
Potato(String color){
this.color = color;
}
/*public String toString(){
return "Name: Potato, Color:"+this.color;
}
*/

}
class Brinjal extends Vegetable{

}
class Tomato extends Vegetable{

}
class TestVegetable{
public static void main(String[] args){
Potato p1 = new Potato("Blue");
Potato p2 = new Potato("Red");

System.out.println(p1);
System.out.println(p2);


}
}