public class Employee{ private String name//姓名 private int salary//薪水
public Employee()
{
//无参构造函数 }
public Employee(String name,int salary)
{ //有参构造函数 this.name=name
this.salary=salary //局部变量若与类变量同名,则以局部变量为准,类变量需要用this引用 }
public void setName(String name){
this.name=name }
public String getName()
{ return this.name
}
public void setSalary(int salary)
{ this.salary=salary }
public int getSalary()
{ return this.salary }}
//测试类
public class Test()
{ public static void main(String args[])
{ Employee e = new Employee("张三",1200)
System.out.println(e.getName())//输出姓名
System.out.println(e.getSalary())//输出薪水
Employee e2= new Employee()
e2.setName("李四")
e.setSalary(1000)
System.out.println(e2.getName())//输出姓名
System.out.println(e2.getSalary())//输出薪水 }
}
*运行结果
张三
1200
李四
1000
*
#include <cmath>#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std
class Employee{
string name
public:
Employee(string nm)
{
name=nm
}
virtual string getName()
{
return name
}
virtual void Display()
{
cout<<"my name is "<<getName()<<", my earing is "<<Earnings()<<endl
}
virtual float Earnings()=0
}
class Boss:public Employee{
public:
Boss():Employee("Boss")
{
}
float Earnings()
{
return 8000
}
}
class HourlyWorker:public Employee{
int Hours
public:
HourlyWorker(int h):Employee("HourlyWorker"){
Hours=h
}
float Earnings()
{
return Hours*100
}
}
class SaleWorker:public Employee{
float sales
public:
SaleWorker(float sals):Employee("SaleWorker")
{
sales=sals
}
float Earnings()
{
return sales*0.05
}
}
int main() {
Employee * emps[3]
emps[0]=new Boss()
emps[1]=new HourlyWorker(100)
emps[2]=new SaleWorker(1000000)
for (int i=0i<3i++)
{
emps[i]->Display()
}
for (int i=0i<3i++)
{
delete emps[i]
}
return 0
}
首先设置一个静态的变量然后设置id变量
然后在构造方法在让这个静态变量自曾 然后把这个静态变量的值赋给id变量 这样每一个新员工都会有一个自己员工号
class Employee{
private String number
private String name
private String birthday
private int ID
static int IDnumber
public Employee(String number,String name,String birthday){
this.setNumber(number)
this.setName(name)
this.setBirthday(birthday)
IDnumber++
ID=IDnumber
}
public void setNumber(String number){
this.number=number
}
public String getNumber(){
return number
}
public void setName(String name){
this.name=name
}
public String getName(){
return name
}
public void setBirthday(String birthday){
this.birthday=birthday
}
public String getBirthday(){
return birthday
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)