java 我想从另一个类调用一个方法,但在同一个包或文件中。如何做到这一点?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31086487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
i want to call a method from another class but in same package or file.how to do this?
提问by Namrata Dhamal
for ex. i have class A class B class C i want to use method defined in class C for objects of class B which is called in Class A. how to do this?
例如。我有 A 类 B 类 C 我想将 C 类中定义的方法用于 A 类中调用的 B 类对象。如何做到这一点?
have look over program? i am getting error at PRint statement?
有查看程序吗?我在 PRint 语句中遇到错误?
package com;
public class CreditCardDemo {
public static void main(String[] args)
{
CreditCardCompany C=new CreditCardCompany();
customer one=new customer(1 , 11 , 1560);
customer two =new customer(2,22,3400);
customer three=new customer(3,33,1600);
customer four=new customer(4,44,600);
customer five=new customer(3,33,100);
System.out.println("Payback amount: "+ getPybackAmount(two));
}
}
回答by T.J. Crowder
If the method you want to call is static
, use the class name, a dot, and the method name:
如果要调用的方法是static
,请使用类名、点和方法名:
TheClass.theMethod();
If it's not static
, then you need an instanceof the class on which to call it:
如果不是static
,那么您需要一个类的实例来调用它:
TheClass t = new TheClass();
t.theMethod();
Note that to use a method of a class from an unrelated class in the same package, the method must not be marked private
. It can have no modifier, protected
, or public
, but it can't be private
. To use it in an unrelated class in a differentpackage, it has to be public
. Details in this tutorial:
请注意,要使用来自同一包中不相关类的类的方法,该方法不得标记为private
。它可以没有修饰符、 protected
、 或public
,但不能是private
。要在不同包中的不相关类中使用它,它必须是public
. 本教程中的详细信息:
The following table shows the access to members permitted by each modifier.
Access Levels Modifier Class Package Subclass World public Y Y Y Y protected Y Y Y N no modifier Y Y N N private Y N N NThe first data column indicates whether the class itself has access to the member defined by the access level. As you can see, a class always has access to its own members. The second column indicates whether classes in the same package as the class (regardless of their parentage) have access to the member. The third column indicates whether subclasses of the class declared outside this package have access to the member. The fourth column indicates whether all classes have access to the member.
下表显示了每个修饰符允许的成员访问权限。
Access Levels Modifier Class Package Subclass World public Y Y Y Y protected Y Y Y N no modifier Y Y N N private Y N N N第一个数据列指示类本身是否可以访问由访问级别定义的成员。如您所见,类始终可以访问自己的成员。第二列指示与该类位于同一包中的类(无论其出身如何)是否可以访问该成员。第三列指示在此包外声明的类的子类是否可以访问该成员。第四列指示是否所有类都可以访问该成员。