0

I have two pieces of code, one required me to create a new object and then call the methods using that object. Yet another code worked without me needing to create the object.

import java.util.Scanner;

public class Wheel
{
    double radius;

    public Wheel (double radius)
    {
        this.radius = radius;
    }

    double getCircumference()
    {
       return 2 * Math.PI * radius;
    }

    double getArea()
    {
        return radius * radius * Math.PI;
    }

    public static void main (String [] args)
    {
        System.out.println("Please enter a number: ");
        Scanner numInput = new Scanner(System.in);
        double num = numInput.nextDouble();

        Wheel r = new Wheel(num);
        System.out.println(r.getCircumference());
        System.out.println(r.getArea());
    }
}

Here is the other.

public class GiveChange
{

    public static int getQuarters(int p)
    {
        return p / 25;
    }

    public static int getDimes(int p, int q)
    {
        return p / 10;
    }

    public static int getNickels(int p, int q, int d)
    {
       return p / 5;
    }

    public static int getPennies(int p, int q, int d, int n)
    {
        return p / 1;
    }

    public static void main(String[] args)
    {
        int pennies = 197;
        int q = getQuarters(pennies);
        pennies -= q * 25;
        int d = getDimes(pennies, q);
        pennies -= d * 10;
        int n = getNickels(pennies, q, d);
        pennies -= n * 5;
        int p = getPennies(pennies, q, d, n);
        String str = String.format("The customer should recieve %d " +
                "quarters, %d dimes, %d nickels, " +
                "and %d pennies.", q, d, n, p);
        System.out.println(str);
    }
}

Is it because the second code has public static int, while the second one just has the data type.

shutdxwn
  • 21
  • 1

2 Answers2

0

The Wheel class defines and instantiates an object to use inside of main. The GiveChange class does not require an object for instantiation since you are working with static methods.

The difference between the two is simple - a Wheel holds state - like the radius of the wheel - but GiveChange does not hold any state in order to do its calculation.

Makoto
  • 104,088
  • 27
  • 192
  • 230
0

Also in the second code if you want to have a GiveChange object you should make new of that. but you are using static methods and you don't need to new object there. For more information about java static methods visit here

Mohsen
  • 4,536
  • 2
  • 27
  • 49