gpt4 book ai didi

java - 我可以在java中隐藏继承层次结构上的变量吗?

转载 作者:太空宇宙 更新时间:2023-11-04 12:00:14 26 4
gpt4 key购买 nike

我正在尝试创建一个程序,其中有一个带有公式的方法。该公式导出到其他类,但每个类使用不同的变量。

当我使用我的程序时,方法和变量会被导出,我只想将方法(公式)从 Bronce 类导出到 Silver 类。

如果我无法隐藏变量,我该如何克服这个问题?

我是java新手

铜级

public  class Bronze  {

// ----------------- Atributes -----------------------

private static final double costDay = 0.12;

public int dayMinutes; // daytime telphone minutes used

public double dayTimeCost; //Total daytime calls cost

// ------------- CONSTRUCTORS (inputs) ---------------

public Bronze(int theDayMinutes ) {
dayMinutes = theDayMinutes;
}
// ------------------ METHODS ------------------------
// Calculate Total daytime calls cost
public double calcDayTimeCost() {

dayTimeCost = dayMinutes * costDay;
return dayTimeCost;
}

//toString method to override that in Object
public String toString(){
return("\nCost of daytime calls = " + costDay + "/min"+
"\n\nTotal daytime calls cost = " + dayTimeCost +
"\n"
);
}

//Returns the type of account
public String type(){
return "Bronze";
}
}

银级

public class Silver extends Bronze {

private static final double costDay = 0.22;

public Silver(int theDayMinutes ) {
super(theDayMinutes );

}
//Returns the type of account
public String type(){
return "Silver";
}

}

主类

import java.util.Scanner;

public class AccountUser {

// ------------------- FIELDS ------------------------

// Create instance of Scanner class
public static Scanner input = new Scanner(System.in);
// variables
public static Bronze bron;
public static Silver silv;

public static int dayMinutes;

// ------------------ METHODS ------------------------

public static void main(String [] args) {

// Input dayMinutes (with error message)
do{
System.out.print("Please daytime telphone minutes used --> ");
dayMinutes = input.nextInt();
if ( dayMinutes <= 0){System.out.print("\n" + "Input value outside the range!!!" + "\n");}
}while( dayMinutes <= 0);


// Create new Bronze instance
bron = new Bronze(dayMinutes);
silv = new Silver(dayMinutes);
// Calculate scheme1, scheme2
bron.calcDayTimeCost();
silv.calcDayTimeCost();


System.out.println(bron);
System.out.println(silv);
}
}

最佳答案

将 costDay 作为该方法的参数。 public double calcDayTimeCost(double costDay) 然后用 silv.calcDayTimeCost(0.22) 调用它

关于java - 我可以在java中隐藏继承层次结构上的变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40976340/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com