user4930411
user4930411

Reputation:

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);

}

Upvotes: 0

Views: 78

Answers (3)

santosh
santosh

Reputation: 21

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.

Upvotes: 0

lyjackal
lyjackal

Reputation: 3984

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);
  }
}

Upvotes: 1

Crazyjavahacking
Crazyjavahacking

Reputation: 9677

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;

Upvotes: 0

Related Questions