简体   繁体   English

使用其他类的方法

[英]Using methods from other classes

The difference between (a) import somePackage.someClass; (a) import somePackage.someClass;之间的区别import somePackage.someClass; and (b) someClass object = new someClass(); (b) someClass object = new someClass(); is that (a) will allow call the methods from the imported class without creating new instances of it, while (b) will create an object using the template class and therefore the methods for the class someClass will belong to the object object . 是(a)允许从导入的类调用方法而无需创建新实例,而(b)将使用模板类创建对象,因此someClass类的方法将属于对象object So if I want to use a method someMethod() from someClass in (b) I'd call it through the object object. 因此,如果我想使用(b)中someClass someMethod()方法,则可以通过object对象调用它。 Is it how it works? 它是如何运作的?

  • Yes you can use static methods from a class directly 是的,您可以直接使用类中的静态方法
  • Yes you can use methods from a class by creating an object 是的,您可以通过创建对象来使用类中的方法

But more important thing than just the above options available is when to use which. 但是,除了上述可用选项外,更重要的是何时使用哪种选项。 First type of call is to class methods whereas the second class is to instance methods. 第一种调用是对类方法的调用,而第二种调用是对实例方法的调用。

Instance Methods vs Class Methods: Each class represents a set of attributes and behaviour. 实例方法与类方法:每个类代表一组属性和行为。 Instance methods usually represent the behaviour. 实例方法通常代表行为。 example if Person is a class and Robb is an object, then robb.weight can be attribute, robb.write() would be an instance method and Person.type() (ans: species) or Person.population (ans: total number of instances) can be class methods. 例如,如果Person是一个类,Robb是一个对象,则robb.weight可以是属性,robb.write()将是一个实例方法,而Person.type()(ans:种类)或Person.population(ans:总数)实例)可以是类方法。

Also you represent instance methods in textual writing as ClassName#instanceMethod and ClassName.classMethods 另外,您在文本编写中将实例方法表示为ClassName#instanceMethod和ClassName.classMethods

No, you are wrong 不,你错了

Simplistically if the class that you want to use is not in the same package then you need to import it, or fully path the class eg java.util.ArrayList . 简而言之,如果要使用的类不在同一package则需要导入它,或完全路径该类,例如java.util.ArrayList

If the methods are not static, then you will need to create a new Instance of the class you want to use. 如果方法不是静态的,则需要创建要使用的类的新实例。

You can use methods from other class directly only if it is a static method. 仅当它是静态方法时,才可以直接使用其他类中的方法。 You will also have to add static in your import statement if you want to use the method name directly without prefixing it will the class name. 如果要直接使用方法名称而不在类名称前添加前缀,则还必须在import语句中添加static。 For non-static methods you have to create instance of the class and then call that method. 对于非静态方法,您必须创建该类的实例,然后调用该方法。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM