2014-07-12 88 views
-2

是否可以通過另一個類使用相同的包來限制一個類的訪問?Java類訪問

例如,我們有兩個類A和B在同一個包中。我想限制在Class B中實例化Class A,可能嗎?

public class A 
{ 
} 

public class B{ 
    public static void main(String[] args) { 
     A obj = new A(); // Shuold not allow to create object of A 
    } 
} 
+0

你的意思是沒有其他班級可以啓動它嗎?像一個私人的構造函數?或只在同一個包中? – pL4Gu33

+0

把這兩個放在一個單獨的包中,使類'A'的構造函數包私有,並在類'B'中創建'public createA()'方法來實例化'A'對象。 –

+0

我不想在類B中創建對象。類A不應該有私有構造函數。 – Srinivasan

回答

-2

當您指定有關私人關鍵字的 類的成員,你讓該成員無法訪問其他人,和 消費者資料庫是從使用它的限制。這是 影響一種隱藏您的程序中 中'更改零件'的實現的方式,作爲庫創建者,您可以在不影響消費者代碼的情況下對其進行修改。此外,一個類的私人 成員只能用於同一類中的方法 From here `package kingsley.java;

class Egg { 
    private Egg() { 
    System.out.println("Egg constructor"); 
    } 
    static Egg makeEgg() { 
    System.out.println("in makeEgg()"); 
    return new Egg(); 
    } 
} 

public class Breakfast() { 
    public static void main(String[] args) { 
    Egg egg1 = new Egg(); //! Error can not Make new Eggs 
    Egg egg2 = Egg.makeEgg(); 
    } 
}` 
+2

好吧,那麼請展示一些可以實現op請求的示例代碼。 – ChiefTwoPencils

2

這將是A類和B類之間的特殊關係,因此,無論

  • 類A指定「我不容許B到實例我」或
  • B類指定「我不能實例化A」

這兩個規範在Java中都是不可能的。

0

假設你有4類A,B,C & D. A可以到C & d訪問,而不是B.

注: A,B & C爲ABC包 。 D在d包

第1步:使一個類的構造函數私人

public class A { 
    private A() { 
    } 

    public void hello() { 
     System.out.println("Hello"); 
    } 
} 

步驟2:實例化一個在B.給你的錯誤構造函數A()是不可見的。

public class B { 

    public static void main(String[] args) { 
     A a = new A(); 
    } 
} 

步驟3:實例化一個用C。給出結果「你好」

import java.lang.reflect.Constructor; 
import java.lang.reflect.InvocationTargetException; 
public class C { 
    public static void main(String[] args) { 
     try { 
      Constructor<A> constructor = A.class.getDeclaredConstructor(new Class[0]); 
      constructor.setAccessible(true); 

      A a = constructor.newInstance(); 
      a.hello(); 

     } catch (NoSuchMethodException | SecurityException | InstantiationException 
      | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

步驟4:現在實例化一個在d(d封裝)。也給結果「你好」

import java.lang.reflect.Constructor; 
import java.lang.reflect.InvocationTargetException; 
import abc.A; 
public class D { 
    public static void main(String[] args) { 
     try { 
      Constructor<A> constructor = A.class.getDeclaredConstructor(new Class[0]); 
      constructor.setAccessible(true); 

      A a = constructor.newInstance(); 
      a.hello(); 

     } catch (NoSuchMethodException | SecurityException | InstantiationException 
      | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

這是因爲Java提供了兩種不同的方法來創建一個類的對象。

  1. ​​只返回私有構造函數。
  2. getConstructors() - API返回所有可用的構造函數private,public,protected & default(僅供包使用)。
+0

你有試過嗎?你想要這樣的東西嗎? – OO7