Krantucket
Krantucket

Reputation: 55

What class has access to my methods?

My question today is about creating an object, and what other classes with have access to its methods. I am trying to learn about threading, but since JPanels don't support threads I have gotten all confused.

I create a simplified class like this:

public class MyMethodClass {
    public MyMethodClass () {
        MyClass myClass = new MyClass();
    }
    public void MyMethod() {
        //do something with the variables
    }
}

so I now have a new class object called myClass (MyClass is another class, its content not important). As they are all public, does myClass have access to MyMethod?

If not, is there a way to pass a copy MyMethodClass to myClass so that it can use myMethod, knowing that MyMethodClass created myClass in the first place?

If the class MyClass was a nested class, does it get access to MyMethod?

Upvotes: 2

Views: 46

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347314

MyClass will not be able to access methods within MyMethodClass unless it creates an instance of it and in this case, that's a bad idea.

You could could pass MyClass an instance of MyMethodClass via its constructor or a setter method, but you'd actually be better using a common interface, which would decouple the two classes and improve its reusability

Start by defining the contract between the two class (as an interface)...

public interface SomeMethods {
    public void MyMethod();
}

Add the ability to pass an implementation of SomeMethods to MyClass via it's constructor or setter method...

public class MyClass {
    private SomeMethods someMethods;
    public MyClass(SomeMethods someMethods) {
        this.someMethods = someMethods;
    }

    public void someWork() {
        someMethods.MyMethod();
    }
}

Have MyMethodClass implement the SomeMethods interface and pass a reference of itself to MyClass

public MyMethodsClass implements SomeMethods {
    public MyMethodClass () {
        MyClass myClass = new MyClass(this);
    }
    @Override
    public void MyMethod() {
        //do something with the variables
    }
}

Just beware, it's generally not considered a good idea to pass this to other classes or methods from within the constructor, as the state of the object may not be fully realised and some value that the methods/classes rely on may not yet be initialised.

Upvotes: 1

Related Questions