How does my below code work? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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

20th Aug 2021, 6:47 AM
Rishi
Rishi - avatar
6 Answers
+ 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"
20th Aug 2021, 10:58 AM
你知道規則,我也是
你知道規則,我也是 - avatar
+ 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.
20th Aug 2021, 11:08 AM
A͢J
A͢J - avatar
+ 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.
20th Aug 2021, 7:52 AM
你知道規則,我也是
你知道規則,我也是 - avatar
+ 2
Rishi That's exactly what my answer is telling, the visibility?
20th Aug 2021, 10:12 AM
你知道規則,我也是
你知道規則,我也是 - avatar
+ 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?
20th Aug 2021, 10:34 AM
Rishi
Rishi - avatar
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
20th Aug 2021, 10:04 AM
Rishi
Rishi - avatar