如何从java中的不同类调用方法以及如何修复“非静态方法不能从静态内容引用“错误? [英] How to call a method from a different class in java and how to fix" non static method cannot be referenced from a static content" error?

查看:158
本文介绍了如何从java中的不同类调用方法以及如何修复“非静态方法不能从静态内容引用“错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I want to call the homeValue method from the house class to the method valOfHouse in the HouseHelper class. I keep getting an error "non static method cannot be referenced from a static content". How can i fix this code? I can only make changes to the HouseHelper class.




public class House 
{ 
public House (String _location, String _realtor, String _color, int _rooms, int _price, int _size, int _year) 
{ 
this.location = _location; 
this.realtor = _realtor; 
this.color = _color; 
this.rooms = _rooms; 
this.price = _price; 
this.size = _size; 
this.year = _year; 
} 
public int homeValue() 
{ 
Calendar calendar= Calendar.getInstance(); 
int ageOfHome = calendar.get(Calendar.YEAR) - year; 
if (ageOfHome <= 0) 
ageOfHome=1; 
int older = ageOfHome * 12000; 
int new = ageOfHome * 10000; 
int val = price; 
if (price > older) 
currentVal -= age * 1550; 
else if (price < new) 
val -= ageOfHome * 1300; 
else 
val -= ageOfHome * 1400; 
return val; 
} 

public class HouseHelper 
{ 


 public int valOfHouse() 
{ int total = 0;
  total = House.homeValue();

 return total; // non static method cannot be referenced from a static content
 }





我的尝试:



公共类HouseHelper < br $>
{





public int valOfHouse()

{int total = 0 ;

total = House.homeValue();



总回报; //非静态方法无法从静态内容中引用

}



What I have tried:

public class HouseHelper
{


public int valOfHouse()
{ int total = 0;
total = House.homeValue();

return total; // non static method cannot be referenced from a static content
}

推荐答案

我建​​议你去 Java教程 [ ^ ]并通过学习指南。
I suggest you go to The Java Tutorials[^] and work through the study guides.


正如错误消息所述,在方法(homeValue())之前class name(House)仅在homeValue()是静态方法时有效,即

As the error message said, preceding a method (homeValue()) with a class name (House) only works if homeValue() is a static method, i.e.
public static int homeValue()



否则,你有首先实例化House类,即


otherwise, you have to instantiate the House class first, i.e.

House house = new House();
int total = house.homeValue();


这篇关于如何从java中的不同类调用方法以及如何修复“非静态方法不能从静态内容引用“错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆