Lee
Lee

Reputation: 1

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

I can't remember what it's called when another class's method in java for example in a main class you call the scanner class to scan in user input?

Upvotes: 0

Views: 1047

Answers (4)

Lou Franco
Lou Franco

Reputation: 89242

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. You say that Main depends on Scanner or Main uses-a Scanner. I made this UML slideshow and cheatsheet:

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.

Upvotes: 1

Alexandr
Alexandr

Reputation: 9515

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
  }
}

Upvotes: 1

stacker
stacker

Reputation: 69002

I think you're looking for the names of associations like aggregation and composition. The terms are used to describe Releationships in UML

Upvotes: 2

Related Questions