*
* @(#)clsdyna.java 1.0 04/12/25
*
* you can modify the template of this file in the
* directory ..\jcreator\templates\template_1\project_name.java
*
* you can also create your own project template by making a new
* folder in the directory ..\jcreator\template\. use the other
* templates as examples.
*
*/
package myprojects.clsdyna;
import java.util.*;
class clsdyna {
public clsdyna() {
}
public static void main(string args[]) {
system.out.println("starting clsdyna…");
person pr=new boy("万青");
person pg=new girl("李敏");
system.out.println(pr.tostring());
system.out.println(pg.tostring());
system.out.println("==========");
personfactory pc=new personfactory("吴波",true,33);
person tc=pc.getperson();
system.out.println(tc.getname());
system.out.println(tc.tostring());
}
}
abstract class person
{
protected string name;
protected boolean sex;
protected int age;
protected int id;
private static int pid;
static {
pid=1000;
}
public static int personid()
{
return pid++;
}
public person(string na,boolean sx,int ag)
{
/*
//it also can write like this
name=na;sex=sx;
age=ag;
id=person.personid();
*/
this(na,ag);
if(!sx)
this.setsex(false);
}
public person(string na,int ag)
{
name=na;age=ag;sex=true;//this(na);
id=person.personid();
}
public person(string na)
{
name=na;age=18;sex=true;
id=person.personid();
}
public int getid()
{
return id;
}
public string getname()
{
return name;
}
public void setname(string na)
{
name=na;
}
public int getage()
{
return age;
}
public void setage(int dg)
{
age=dg;
}
public boolean issex()
{
return sex;
}
protected void setsex(boolean sx)
{
sex=sx;
}
public string tostring()
{
return "id:"+id+";name:"+name+";age:"+age+";sex:"+ (sex?"男":"女");
}
abstract void sayhello();
}
class boy extends person
{
public boy(string na,int age)
{
super(na,age);
this.setsex(true);
}
public boy(string na)
{
super(na);
this.setsex(true);
}
public void sayhello()
{
system.out.println(this.tostring());
}
}
class girl extends person
{
public girl(string na,int age)
{
super(na,age);
this.setsex(false);
}
public girl(string na)
{
super(na);
this.setsex(false);
}
public void sayhello()
{
system.out.println(this.tostring());
}
}
class personfactory
{
protected person pboygirl;
public personfactory(string na,boolean sx,int ag)
{
if(sx)
pboygirl=new boy(na,ag);
else
pboygirl=new girl(na,ag);
}
public person getperson()
{
return pboygirl;
}
}
============================
本人刚学java没几天,不对之处请ggjjddmm多多指教
若有兄弟不弃,愿意一起成长的请留qq;另请注明:java study