Wednesday, June 01, 2005

Polymophism

Hey,

I was wondering about Java and polymorphism. Actually, I am waiting for that the QA team to test my software so I can correct bugs and I was freaked out because I thought I could forget
OOP and Java so I thought I should try a little of it. :-)

I basically think of an abstract class A and derive B and C so I can have a 4th class that may use
any of the other 3 and I only write one implementation...


public abstract class A {

A( int a, int b ){};
public abstract void f1();
}

public class B extends A {

protected myC;

B( int a, int b, int c ){
super( a , b );
myC = c;
};

public void f2(){
//
};

public void f2b(){
//
};
}


public class C extends A {

protected String s;

C( int a, int b, String s ){
super( a , b );
this.s = s;
}

public void f2(){
//
}
}

public class D {

A aptr;

D( A a ){

// points to class A
// but knows which derived class it refers to
// because of the polymorphism
aptr = a;

}

void DoSomething(){
a.f2();
}

}

public class E{
public static void main( String[] args ){
B b = new b( 1 , 2 , 3 );
C c = new c( 1 , 2 , "asdasdd" );
D d1 = new D( b );
D d2 = new D( c );

}
}




No comments: