简体   繁体   中英

While passing an attribute typed class as a parameter to a method, is it possible to access it without setters?

For example, let's say I have a base class:

package test;

public class Class1 {
    
    private int attribute1;
    private int attribute2;
    
    public Class1(int att1, int att2) {
        this.attribute1 = att1;
        this.attribute2 = att2;
    }
    
}

Then I'll have another class:

package test;
    
public class Class2 {
        
    private int attribute3;
    Class1 class1;

    public Class2(int att3){
        this.attribute3 = att3;
    }

    public void insert(Class1 class1) {
        //
    }
    
}

Inside the insert method, I'll be passing as a parameter an attribute of type Class1. Is it possible to access Class1 attributes without setters? if yes, how do I do it? Also:

package test;

public class Class2 {
    
    public static void main(String[] args) {
    
        Class2 c2 = new Class2 ();
        
        c2.insert();
    }

}

How should I use the.insert() method? Like, what parameters? I'm a bit confused but this is how my program is supposed to go.

Is it possible to access Class1 attributes without setters?

Surely you mean 'getters'. setters set the value, getters the get the value.

The answer is: No. The 2 attributes are marked private .

How should I use the.insert() method?

Class1 c1 = new Class1();
Class2 c2 = new Class2();
c2.insert(c1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM