简体   繁体   English

在Java的另一个类中使用一个类的变量

[英]using a variable of a class in another class in java

Hello i am new to programming. 您好,我是编程新手。 I have a basic doubt, hope it's not silly. 我有一个基本的疑问,希望这不是愚蠢的。 I have 2 classes, my first class named dialytravel calculates money spend in travel on one day. 我有2节课,我的第一节课叫做dialytravel计算一天的旅行花费。 In my second class names weaklytravel I want to use the sum(from the dailytravel class) to calculate the weakly cost for traveling. 在我的第二个类别“ weaklytravel我想使用sum(来自dailytravel类)来计算差旅费用。 my code is bellow 我的代码在下面

Public class dailytravel {

      private int morning = 3;
      private int evening = 3;
      private int sum;
      sum = morning+evening;

      System.out.println("The money sent for travel in one day" +sum);
}

Below is my second class named weaklytravel. 下面是我的第二节课,名字叫weaklytravel。 How can I use sum in this class. 我如何在这门课中使用sum。

Public class weaklytravel {

      private int noofday = 5;
      private int weakly ;

      weakly = sum * noofdays;
      System.out.println("The money sent for travel in one weak" +weakly);

}

This code is a big mess. 这段代码很乱。 Have you looked at any online courses? 您看过任何在线课程吗? This post might be a place to start: Is there something like Codecademy for Java . 这篇文章可能是一个开始的地方: 是否有Codecademy for Java之类的东西

In java the visibility modifiers are private , public , and none. 在Java中,可见性修饰符为privatepublic和none。 If you have no modifiers, then the variable is accessible by classes in the same package. 如果没有修饰符,则同一包中的类可以访问该变量。 Also, only variable declarations can be defined outside of methods. 同样,只能在方法外部定义变量声明。 In order to access the variable you will need a reference to the dailytravel that has the sum . 为了访问该变量,您将需要引用具有sumdailytravel

Public class weaklytravel {

      private int noofday = 5;
      private int weakly ;
      public void printWeekly(dailytravel daily) {
          weakly = daily.sum * noofdays;
          System.out.println("The money sent for travel in one weak" +weakly);
      }
}


public class dailytravel {

  private int morning = 3;
  private int evening = 3;
  int sum;
  public void printSum() {
      sum = a+b
      System.out.println("The money sent for travel in one day" +sum);
  }
}

In java the private modifier makes your method or field only visible to the class where it is defined. 在java中, private修饰符使您的方法或字段仅对定义它的类可见。

You need to make it more visible: 您需要使其更加可见:

public int sum;

you can use setter and getter method for 'private int sum' and within the getSum you can calculate by using this 您可以将setter和getter方法用于“ private int sum”,并且可以在getSum中使用此方法进行计算

public int getSum() {
        return a+b;
    } 

this method you can use in weaklytravel class for calculation. 您可以在弱旅行类中使用此方法进行计算。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM