简体   繁体   English

如何在Java中从另一个类(非继承)调用一个类?

[英]How do I call a class from another class(not inheritance) in Java?

我不记得当在Java中另一个类的方法(例如在主类中)调用扫描程序类以在用户输入中进行扫描时调用的名称吗?

I think you're looking for the names of associations like aggregation and composition. 我认为您正在寻找聚合和组合等关联的名称。 The terms are used to describe Releationships in UML 这些术语用来描述Releationships在UML

If the scan method is an instance (object) method (not static), it would be something like this 如果扫描方法是实例(对象)方法(非静态),则可能是这样的

Scanner s = new Scanner();
s.scan();

If scan is static (a class method), then 如果扫描是静态的(类方法),则

Scanner.scan();

Edit: The name of the relationship is Dependency in UML. 编辑:关系的名称是UML中的依赖关系。 You say that Main depends on Scanner or Main uses-a Scanner. 您说Main取决于Scanner或Main用途-Scanner。 I made this UML slideshow and cheatsheet: 我制作了以下UML幻灯片和备忘单:

http://www.loufranco.com/blog/files/UMLCheatsheet.html http://www.loufranco.com/blog/files/UMLCheatsheet.html

If you have a Scanner member in the main class, then this is usually called has-a, composition, or an association. 如果您在主类中有一个Scanner成员,则通常称为has-a,composition或association。

Your question is not clear. 您的问题不清楚。

but maybe the following example will help: 但以下示例可能会有所帮助:

class Scanner{
  public void scan(){}
}

//use inheritance
class SubScanner extends Scanner{
  public void scan(){}       //overriding
  public void scan(int i){}  //overloading
}

//use aggreagation
class MainClass{
  private final Scanner scanner;
  MainClass(Scanner scanner){
    this.scanner = scanner;
  }
  public void scan(){ 
    scanner.scan();         //delegation call
  }
}

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

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