简体   繁体   中英

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. In my second class names weaklytravel I want to use the sum(from the dailytravel class) to calculate the weakly cost for traveling. 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. How can I use sum in this class.

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 .

In java the visibility modifiers are private , public , and 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 .

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.

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

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

this method you can use in weaklytravel class for calculation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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