有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

安卓在Java中,当您有一个带有未指定可见性关键字的方法时会发生什么?

我已经在安卓系统上工作了几年,没有一次有老师或任何人告诉我该做什么。 这段时间我一直在想这个

当你有一个方法,我通常看到

public void method(){
//Stuff
}

private void method(){
//stuff
}

我知道void是一个没有返回值的方法,public在某种程度上是该方法的可见性,但是如果我只是使用这样的方法,这会有什么关系吗

void method(){
//stuff
}

因为那样的话,方法的可见性就只是默认的了

我不知道我是否正确,指定“公共”或“私人”只是一种良好的做法吗


共 (3) 个答案

  1. # 1 楼答案

    Java有四个可见性级别:公共、受保护(默认)、私有

    1. 对包裹可见。默认值。不需要修改器
    2. 仅对类可见(私有)
    3. 对世界可见(公众)
    4. 对包和所有子类可见(受保护)

    enter image description here

    默认访问修饰符-无关键字:

    Default access modifier means we do not explicitly declare an access modifier for a class, field, method etc.

    A variable or method declared without any access control modifier is available to any other class in the same package. The default modifier cannot be used for methods, fields in an interface.

    专用访问修饰符-专用:

    Methods, Variables and Constructors that are declared private can only be accessed within the declared class itself.

    Private access modifier is the most restrictive access level. Class and interfaces cannot be private.

    Variables that are declared private can be accessed outside the class if public getter methods are present in the class.

    Using the private modifier is the main way that an object encapsulates itself and hide data from the outside world.

    公共访问修饰符-公共:

    A class, method, constructor, interface etc declared public can be accessed from any other class. Therefore fields, methods, blocks declared inside a public class can be accessed from any class belonging to the Java Universe.

    However if the public class we are trying to access is in a different package, then the public class still need to be imported.

    Because of class inheritance, all public methods and variables of a class are inherited by its subclasses.

    受保护的访问修饰符-受保护:

    Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.

    The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected.

    Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class from trying to use it.

  2. # 2 楼答案

    Java有四个可见性级别:public、protected(默认)、private。其含义如下:

    1. public-使您的方法可供任何其他类访问
    2. protected-使同一包中的任何类或类的任何子类都可以访问您的方法
    3. (默认设置,即没有修饰符)-使您的方法仅可供同一包中的类访问
    4. private-使您的方法仅可供当前类访问

    在类、方法和字段上指定访问修饰符时,同样的规则也适用

  3. # 3 楼答案

    不指定任何内容具有特定含义:

    • public-任何类都可以访问此成员
    • protected-子类可以访问此成员(以及同一类或同一包中的代码)
    • private-只有同一类中的代码才能访问此成员
    • 无(“默认”访问)-只有同一中的代码才能访问此成员

    可以说,上一个案例应该有自己的关键词,但我们现在只能用它了。除非你真的想使用默认的可见性,否则不指定任何东西都是不好的——你真的出于某种原因需要包的可见性,还是你只是默认了所有东西的包可见性?最佳实践是明确地将private用于非公共成员,除非您需要其他成员之一