我无法从另一个类访问String,我不知道我能做到多么简单。例如,我有一个名为“Person”的类,我有一个String名称。我通过构造函数直接设置名称的“名称”。我还有另一个名为Loan的课程,我还没有尝试访问任何内容。我的最后一堂课叫做“App”,这就是一切都完成的地方。
Btw - Person是我的超类,Loan扩展了Person,而App扩展了Loan,它们都在同一个包中。
现在在我的App类中,我尝试访问我所做的ONLY人物对象的字符串“name”。我再次通过构造函数直接分配了名称,但不知怎的,这不起作用。最初我的名字设置受到保护,因为我理解它: protected =访问同一类,相同包或子类中的方法/变量 甚至在我公开我的字符串后,它仍然无法正常工作。我完全失去了......
当我输入
时 System.out.println(omid.name);
它表示它无法解析为变量,我需要创建一个本地变量。
谢谢!
这是我的代码:
package Programs;
public class Person {
public String name;
protected int age;
protected int id;
protected String status;
protected int alienNumber;
protected int socialSecurityNumber;
Person()
{
}
Person(String name, int age, int id)
{
this.name = name;
this.age = age;
this.id = id;
}
public void setid(int id)
{
if(id >= 100000)
{
this.socialSecurityNumber = id;
System.out.println("You are now a citizen " + name);
System.out.println("Social Security Number: " + socialSecurityNumber);
}
else
{
System.out.println("Sorry " + name + " you do not meet the qualitifactions for citizenship");
alienNumber = id;
System.out.println("You alien number is: " + alienNumber);
}
}
public String toString()
{
if(id >=99000 )
{
status = "citizen";
}
else
{
status = "immigrant";
}
return "Name: " + name +
"Age: " + age +
"Id: " + id +
"Status " + status;
}
public static void main(String[] args)
{
Person omid = new Person("omid nassir", 28, 120000);
omid.name = "omid";
}
}
贷款代码
package Programs;
import Programs.Person;
public class Loan extends Person{
public static final int LOANAMOUNT1 = 250000;
public static final int LOANAMOUNT2 = 500000;
public static final int LOANAMOUNT3 = 750000;
public static final int LOANAMOUNT4 = 1000000;
public int income;
public int loanRequested;
Loan(int income, int socialSecurityNumber, int loanRequested)
{
this.income = income;
this.socialSecurityNumber = socialSecurityNumber;
this.loanRequested = loanRequested;
}
public void applyForLoan(String name, int socialSecurityNumber, int income, int loanAmount)
{
int obtainable = LOANAMOUNT1 / 4;
if(socialSecurityNumber >= 99999)
{
if(income > obtainable)
{
obtainable = loanAmount;
System.out.println("Congradulations " + name + " you are eligible for loan amount of " + loanAmount);
}
}
else if(socialSecurityNumber <=99999)
{
obtainable = LOANAMOUNT1;
System.out.println("Sorry " + name + " in order to qualify for " + loanAmount + " you need to be"
+ " a citizen and have a minimum income of " + obtainable);
System.out.println("Loan amount granted: " + LOANAMOUNT1);
}
}
}
应用代码
package Programs;
public class App extends Person {
public static void main(String[] args)
{
System.out.println(omid.name);
}
}
答案 0 :(得分:1)
您需要在omid
中的main
方法中定义App
。您在omid
的{{1}}内定义了main
,但无法访问此变量,因为这是一个完全不同的范围。您可能想要阅读Person
及其语义。
答案 1 :(得分:0)
您有多种static void main()
方法。只运行App
中的一个。我看到App extends Person
;我不认为这就是你想要的。静态方法不能被覆盖;它不会在Person
中自动调用您的main方法。在您的程序中执行的唯一语句是
System.out.println(omid.name);