简体   繁体   English

为什么我们不能在Java文件中访问非公共类的方法?

[英]Why can't we access methods of non-public classes inside a java file?

class Basics415 {   

    public static void main_hooo(){
        out.println("1234");    
    }

    void main_ho(){
    }       
}

In another file called Basics5.java: 在另一个名为Basics5.java的文件中:

public class Basics5 extends Basics415{   

    public static void main(){
        main_hooo();        // We are accessing a public method of Class Basics415 
        main_ho();  // BUT WE CANNOT ACCESS A NON PUBLIC METHOD FROM SAME CLASS 
    }       
}

Why can't we access main_ho() while we can access main_hooo() ? 为什么在访问main_ho()时不能访问main_hooo()

Why basic415.main_ho or Basic415.main_hooo doesn't work inside the main method of Basics5? 为什么basic415.main_ho或Basic415.main_hooo在Basics5的main方法中不起作用?

Because the methods are static and therefore the classes need are needed to access them. 由于方法是静态的,因此需要类来访问它们。

Basics4.method_Inside_Basics4()

So, after you edited a bunch of code ... 因此,在您编辑了一堆代码之后...

public class Basics5 extends Basics415{   

    public static void main(){
        // accessing a static method in a static context.
        Basics415.main_hooo();

        // accessing an instance method in a static context.
        final Basics415 b = new Basics415();
        b.main_ho();
    }       
}

你的问题是,类Basics5主要梅托德是,静态方法是在类级别而不是实例级别定义的静态方法,那么你就不能使用这种方法在静态方法不是一成不变的。

You should access method_Inside_Basics4 method as Basics4.method_Inside_Basics4(). 您应该以Basics4.method_Inside_Basics4()的方式访问method_Inside_Basics4方法。 As Basics5 class extends Basics415 class, it inherits main_hooo method, which can be assessed from Basics5. 随着Basics5类扩展Basics415类,它继承了main_hooo方法,可以从Basics5对其进行评估。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java Applet无法访问同一Web服务器上的非公共文件 - Java applet can't access non-public file on same webserver 从JDK访问非公共(Java本地)类(7) - Access non-public (java-native) classes from JDK (7) 为什么Java 8不允许使用非公共默认方法? - Why does Java 8 not allow non-public default methods? 如何在.java文件中为非公共类生成Javadoc - How to generate javadoc for non-public classes in a .java file 为什么我们不能在非泛型类中使用泛型方法? - Why can't we have generic methods inside non-generic classes? 使用JMockit在抽象类中模拟非公共静态方法? - Mocking non-public static methods in abstract classes with JMockit? 为什么有很多非公开的低级Java方法以0结尾? - Why are there a lot of non-public low-level Java methods ending in 0? 为什么我可以从另一个包访问非公共的javax.swing.Box.Filler? - Why can I access the non-public javax.swing.Box.Filler from another package? 为什么我可以在main中使用外部非静态类和方法,而不能使用类中定义的类和方法? - Why can I use external non static classes and methods inside main, and can't with classes and methods defined inside the class? 通过模式访问非公共方法 - Accessing non-public methods through patterns
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM