When to use separate package in java?

2020-07-17 07:49发布

Sometimes when I view source java code I notice some files placed in another package besides the default one but have not understood when or why this practice is used. Are there situations where you must or mustn't use separate packages? Anyone care to explain please?

标签: java package
7条回答
▲ chillily
2楼-- · 2020-07-17 08:22

When to Use Separate package in java:

Lets us take an example in favor of this question.

Suppose you have an java program that deals with the database connectivity also it need two separate threads to perform this task and also it need some arraylist to store the database information that has been retrieved from the database. in this case it's very easy to use package.If I need database package I know that where it it I will simply import my java.sql package

If I have to handle with thread I will use java.lang.Thread package. And I have to deal with arraylist then I will use my java.util package. Think how it is simple to just import package based on your need.

Moreover suppose you implement your own package that performs addition ,multiplication,subtraction of two numbers.that what you will do can create a simple package that will deal with these operations.and everywhere you can use this package where ever you will be in need of those operations then you will need not to write code for these operations every time in your application.

e.g

package Arithmetic;

  public class Operations
  {
   public long sum(long a ,long b)
   {
     return a+b;
   }
   public long subtraction(long a,long b)
   {
     return a-b;
   }
   public long multiply(long a,long b)
   {
    return a*b;
   }
 }

Now I can use this package into by another class

   import Arithmetic.*;
   class Demo
   {
     public static void main(String...k)
     {
       Operations op=new Operations();
       System.out.println(op.sum(12,23));
       System.out.println(op.multiply(23,23));
       System.out.println(op.subtraction(342,23));
     }
   }
查看更多
登录 后发表回答