1. Static and Final Keywords
private staticRandomrand=newRandom();
static classJob {
private final inta;
/*private final static int a;
ERROR:Can not add static because static
member variable will be initialized
before the constructor loaded*/
Job() {
a=rand.nextInt(12);//Final member variable initialized here
}
intGet(){
return this.a;
}
}
public static voidmain(String[] args) {
Job a =newJob();
Job b =newJob();
print(a.Get());
print(b.Get());
}
2.Polymorphism and Dynamic Binding
importjava.util.Random;
import staticnet.mindview.util.Print.print;
classRodent{
public voidmyFood(){};
}
classMouseextendsRodent{
public voidmyFood(){
print("Grain is my favorite");
}
}
classGerbilextendsRodent{
public voidmyFood(){
print("Grass is my favorite");
}
}
classHamsterextendsRodent{
public voidmyFood(){
print("Peanut is my favorite");
}
}
classRodentParadise{
privateRodent[]buildingNest() {
Random rand =newRandom();
Rodent[] myWarmNest =newRodent[7];
for(inti =0;i < myWarmNest.length;i++){
switch(rand.nextInt(3)){
default:
case0:myWarmNest[i] =newMouse();continue;
case1:myWarmNest[i] =newGerbil();continue;
case2:myWarmNest[i] =newHamster();continue;
}
}
returnmyWarmNest;
}
publicRodent[]getNest(){
returnbuildingNest();
}
}
public classExercise {
public static voidmain(String[] args) {
RodentParadise n =newRodentParadise();
for(Rodent x:n.getNest()){
x.myFood();
}
}
}