![](/img/trans.png)
[英]How to implement a thread-safe class with a setter and a getter function where the frequency of using setter is way higher than getter
[英]Getter and Setter Function Help and How To
我目前正在编写一个程序,其中需要合并get函数以生成和输出该程序。 该程序需要将Numbers SeatsA = 30,pricePerSeatA = 120.99。 我以为我的程序设置方法是调用这些函数,然后设置数量然后打印。 我试过使用ConcertSales ConcertSales = new ConcertSales(); 但是只要我准备调用该函数,就可以使用ConcertSales.getNumberOfSeatsTypeA();。 或ConcertSales.setNumberOfSeatsTypeA(30),它给我一个错误消息。 我究竟做错了什么? 请帮忙! 这是我的代码:
public static void main(String[] args) {
class ConcertSales{
ConcertSales concertSales = new ConcertSales();
public int numberOfSeatTypesA;
public int numberOfSeatTypesB;
public double pricePerSeatA;
public double pricePerSeatB;
public double totalSales;
public int getNumberOfSeatTypesA()
{ return numberOfSeatTypesA;}
//did the same for Types B
public void setNumberOfSeatTypesA(int newValue)
{ numberOfSeatTypesA = newValue; }
//same done for SeatsB
public double computeTotalSales()
{ return totalSales = numberOfSeatTypesA*pricePerSeatA +
numberOfSeatTypesB*pricePerSeatB }
}
concertSales.setNumberOfSeatTypesA(30); //this is where i keep getting
my error messages.
任何帮助表示赞赏! 谢谢
我认为您是Java初学者,还是OOP初学者。 在Java中,所有函数/方法都应在类内部,甚至应包含在主函数中。
这是代码:
class ConcertSales{
public int numberOfSeatTypesA;
public int numberOfSeatTypesB;
public double pricePerSeatA;
public double pricePerSeatB;
public double totalSales;
public int getNumberOfSeatTypesA(){
return numberOfSeatTypesA;
}
public void setNumberOfSeatTypesA(int newValue){
numberOfSeatTypesA = newValue;
}
public double computeTotalSales(){
return totalSales = numberOfSeatTypesA*pricePerSeatA +
numberOfSeatTypesB*pricePerSeatB;
}
public static void main(String[] args) {
ConcertSales concertSales = new ConcertSales();
concertSales.setNumberOfSeatTypesA(30);
System.out.println(concertSales.getNumberOfSeatTypesA());
}
}
您是否将类写入main方法?
反过来说,您的类包含一个main方法
一些东西:
您不需要ConcertSales ConcertSales = new ConcertSales(); 因为Java会自动构造默认的构造函数。 该行应移至您的主程序中。
您应该将ConcertSales类移到main之外。 最好在另一个文件中。
假设您为ConcertSales创建了一个单独的类,则主类如下所示。
public static void main(String[] args) { ConcertSales sales = new ConcertSales(); // create new ConcertSales object sales.setNumberOfSeatTypesA(30); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.