我想创建一个具有成员函数(例如 giveCharity)的类(例如 Person),但我希望该方法的内容对于该类的每个实例都不同,从而模仿人工智能。这可能吗?我将何时以及如何为每个实例的方法填充代码?
这是一个例子:
public class Person
{
// data members
private int myNumOfKids;
private int myIncome;
private int myCash;
// constructor
public Person(int kids, int income, int cash)
{
myNumOfKids = kids;
myIncome = income;
myCash = cash;
}
// member function in question
public int giveCharity(Person friend)
{
int myCharity;
// This is where I want to input different code for each person
// that determines how much charity they will give their friend
// based on their friend's info (kids, income, cash, etc...),
// as well as their own tendency for compassion.
myCash -= myCharity;
return myCharity;
}
}
Person John = new Person(0, 35000, 500);
Person Gary = new Person(3, 40000, 100);
// John gives Gary some charity
Gary.myCash += John.giveCharity(Gary);