我是一个新的java学习者,我正在制作一个程序,我想在静态方法中访问非静态数据成员的值,但规则说我不能这样做,但我们可以在创建对象后访问它我的问题是如果我创建该类的对象,该数据成员的旧值将被擦除,为什么?我如何在静态方法中使用非静态数据成员的旧值
import java.util.Scanner;
class emp
{
String name;
int rate;
static String c_name="TCS";
void setdata(String n,int s)
{
name=n;
rate=s;
}
static void employee_salary_cal(int t)
{
int day,rate1,Total;
day=t;
emp e2=new emp();
rate1=e2.rate;
Total=rate1*day;
System.out.println("Total salary " +Total);
}
void showData()
{
System.out.println("Employee name = " +name);
System.out.println("Employee pay rate per day = " +rate);
}
}
class emp_main
{
public static void main(String args[])
{
int da;
emp e1=new emp();
e1.setdata("alex",100);
System.out.println("Company name = " +emp.c_name);
e1.showData();
System.out.println("Enter Work days in months ");
Scanner sc=new Scanner(System.in);
da=sc.nextInt();
emp.employee_salary_cal(da);
}
}
程序输出:
Company name = TCS
Employee name = alex
Employee pay rate per day = 100
Enter Work days in months
25
Total salary 0