0
How does my below code work?
In my function below, how is the function LoadingMessage() accessible from outside the class? https://code.sololearn.com/cvaHs8HlxTWM/?ref=app
6 odpowiedzi
+ 2
Rishi Yes, for example:
---in anotherClass.java---
package test;
public class anotherClass
{
void function() {System.out.println("42");}
}
---in MyClass.java---
import test.anotherClass;
public class MyClass {
public static void main(String args[]) {
anotherClass x = new anotherClass();
x.function();
}
}
output: "error: function() is not public in anotherClass; cannot be accessed from outside package"
+ 5
Rishi
You can access methods through class object. So you have created an object of class Loading and accessed method through that object.
One more thing in Java it's method not function. In JavaScript it is function though both do same thing.
You can access static method directly through class name. No need to create object for static methods.
+ 2
The default visibility of class is package private. It's accessible from the same package the class belongs to. There is no equivalent keyword for that. You use the visibility when you don't explicitly define one.
+ 2
Rishi That's exactly what my answer is telling, the visibility?
+ 1
CarrieForle you mean that, if I tried something like
....
Loading loading=new Loading();
loading.LoadingMessage();
....
From another package, it'll result in a compilation error?
0
CarrieForle okay but, I'm asking about the visibility of the function inside the class (method). In my code, the function *LoadingMessage()* is accessible outside the class *Loading*, that's what I don't understand