Define a package named temperature and create a class named Conversion that has a method which converts the temperature from Fahrenheit to Celsius. Define a package named mypack and create a class that has method which calls methods of Conversion class of temperature package.
Objective
Write a Java program to define a custom temperature conversion package and call it from another package.
Algorithm / Approach
- Create a class named
Conversion. - Declare its package as
package temperature;. - Add a
publicmethod to convert Fahrenheit to Celsius. - Create a
Testclass and declare its package aspackage mypack;. - Import the temperature package:
import temperature.*;. - In the main method, instantiate the
Conversionclass and execute the conversion.
Conversion.java
// File 1 - Conversion.java
package temperature;
public class Conversion {
public double convert(int f) {
double c = 5.0/9*(f-32);
return c;
}
}
// File 2: Test.java
package mypack;
import temperature.*;
import java.util.Scanner;
class Test {
public static void main(String[] a)
{
Conversion c=new Conversion();
Scanner s=new Scanner(System.in);
System.out.print("Enter Temp in (F): ");
int f = s.nextInt();
double res = c.convert(f);
System.out.print("Temp in Cel. = "+res);
}
}
Expected Output
Enter Temp in (F): 50 Temp in Cel. = 10.0
Explanation of the Program
- This program reinforces how packages act as namespaces. The
temperaturepackage houses our mathematical utility. - Crucially, the
convert()method inside theConversionclass MUST be marked aspublic. - If you omit the
publicaccess modifier, the method will default to "package-private", meaning it can only be accessed by other classes inside thetemperaturepackage, and theTestclass inmypackwould throw an error.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)