public class Human
{
private String name;
public Human()
{
name="";
}
public void setName(String g)
{
name=g;
}
public String getName()
{
return name;
}
}
-------------------------------------------------------------------------------------
public class People extends Human
{
private int age;
public People()
{
super();
age=0;
}
public void setAge(int nn)
{
age=nn;
}
public int getAge()
{
return age;
}
public String toString()
{
return("age is "+age);
}
}
-----------------------------------------------------------------------------
import
java.util.Vector;
import javax.swing.*;
public class TestPeople
{
Human hu;
People vv, tt;
Vector pep;
String out=" ";
public TestPeople()
{
// --------casting reference types upo and down the heirarchy--------------
People p1=new People();
Human h1=new Human();;
h1=(Human)p1;
h1.setName("paul");
// h1.setAge(22); // ERROR
out+=h1.getName();
People p2=(People)h1;
p2.setName("larry");
p2.setAge(33);
out+=p2.getName()+p2.getAge()+'\n';
// example of assignment conversion of reference types
Human h3=new Human();
People p3=new People();
h3=p3; // asign the type of p3 object to h3 -- h3 is now a People object
//-------------------------------------------------------------------
int a,b,c;
pep=new Vector(10);
for(a=0;a<pep.capacity();a++)
{
pep.add(a, new People()); // create 10 People objects and put ref in vector
}
// fill all objects with dummy ages 10 thru 100
// all references to pep in the code below could be preceeded by "this"
// if multiple vextors existed (??) like an array of TestPeople
for( b=10,c=0;b<=100;b+=10,c++)
{
tt=(People)pep.remove(c); // notice the casting
tt.setAge(b);
pep.add(c,tt);
}
// pull them out backwards and concatenate to print
for(c=9;c>=0;c--)
{
tt=(People)pep.remove(c);
out+=tt.getAge()+" ";
test_print(tt);
}
JOptionPane.showMessageDialog(null,out);
}
public void test_print(Object obj) // anything can be passed and received as an object
{
vv=(People)obj;
System.out.println(vv);
}
public static void main(String[] args)
{
new TestPeople();
}
}