• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Why activity class should (usually) be Public class?

Bee Torika

Newbie
Hi ,

Why activity class should (usually) be Public class? (Android)

Because public class can be accessible from other package.

And other package usually means other application, right?

Then, why activities allow other application's accesses ?

It looks not good for security.

But so many projects and examples declare activities as public.

Why not default scope?
In default scope, other project can not access the activity and classes in project can access the activity freely.

At least, activity that contains onCreate(Bundle bundle) will be better if it is declared as default scope, right ?

plz tell me what is wrong with my thinking, so that I could know about android much more.
 
It needs to be public, because your activity class does need to be accessed from another package. You have to realise that your app is not running in isolation on the system. In fact your app is not even a stand alone program - it has no main() method right? The app code is run by the Android app management system, which calls methods on your code - such as onCreate(). Therefore this code has to be accessible.

However there is no danger of other apps accessing your code, because the class loader doesn't allow it. Each app effectively has its own classpath, which is used to dynamically load classes.
Say for example my app had package name

A.B.myapp

and some other app was installed on the system with package name

C.D.otherapp

There is no way that myapp could load classes from C.D.otherapp (even if it did know the package name) because the class loader prevents it. If an attempt like that was made, myapp would get a ClassdefNotFound exception.
 
Back
Top Bottom