2014-04-27 128 views
-3

我创建了一个java类,例如class1来定义一个存储在内存某处的对象。我想使用另一个班级访问该对象,如class2。我如何访问我在class1中从class2定义的那个对象及其实例?谢谢。访问java中的对象

回答

2

首先,在Java中我们通常使用大写字母(Class1Class2

public class Class1 { 
    //... 
} 

public class Class2 { 
    public static void main(String[] args) { 
     Class1 c = new Class1(); 
    } 
} 

这意味着你通过一个构造访问内部的Class2的Class1的对象开始的类名称。

在我的例子中我使用的是默认的构造函数,但你也可以在你的Class1像定义其他构造与参数:

public class Class1 { 
    private String s1, s2; 
    public Class1(String s1, String s2) { 
     // do something (in general assign s1 and s2 to attributes s1 and s2 
    } 
} 
1

假设你有一个电话,想让你的朋友使用的是电话。你是做什么?你给它电话,对吧?与Java对象相同。

Foo foo = new Foo(); 
Bar bar = new Bar(foo); 
// now bar has a reference to the foo object, and can use it in every method. 

Foo foo = new Foo(); 
Bar bar = new Bar(); 
bar.doSomethingWithFoo(foo); 
// now doSomethingWithFoo() has a reference to the foo object, and can use it. 

更具体:

Phone phone = new Phone(); 
Friend friend = new Friend(); 
friend.makeAPhoneCall(phone); 
0

要么让有型class1class2这样的领域:

public class class2{ 
    class1 my_obj; 

    //other code 
} 

,你可以ACCE SS这样的:

class2 my_obj_c2 = new class2(); 
my_obj_c2.my_obj = new class1(); 

您也可以通过方法来访问该对象:

class2 ex_obj = my_obj_c2.getClass1Obj(); 

,其中该方法具有这样的声明:

public class1 getClass1Obj(){ 
    return my_obj; 
} 

使用方法,如果你没有或者不想在class2内的这个class1对象上使用较低的特权。

0

如果我找到了你,在class2中你可以定义class1的属性。

public class Class2 { 
    private Class1 myclass; 

    public void setmyclass(Class1 myclass1) { 
    this.myclass = myclass1; 
    } 
    public Class1 getmyclass() { 
    return this.myclass; 
    } 
} 

然后主要或任何你想要你的地方。

Class1 mycreatedclass1 = new Class1(); 
Class2 mycreatedclass2 = new Class2(); 
mycreatedclass1.setmyclass(mycreatedclass2);