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

时间:2016-12-05 14:17:22

标签: java inheritance

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

当我使用我的程序时,会导出mothods和变量,我只想将方法(公式)从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);
    }
}

0 个答案:

没有答案