2

I wanted to know how a static method is called in another class.

Assume I have a class as following,

class classA
{
public static void method1(String a)
{
}
}

In another class the method method1 is called as following,

class classB
{
public static void main(String[] args)
{
 method1("Alpha");
 }
 }

Please note that the ClassB is not extending the ClassA, I am confused.

Andrei Botalov
  • 19,996
  • 11
  • 86
  • 122
Fazy
  • 563
  • 1
  • 5
  • 16

4 Answers4

4

You can use a static import:

import static yourpackage.classA.method1;

For more information see: http://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html

If you are working in default package, the import will fail, see: https://stackoverflow.com/a/1964006/2039482

Side note: Class names are conventionally always starting with an upper case letter

Community
  • 1
  • 1
bpoiss
  • 13,142
  • 3
  • 33
  • 48
1

If you have in your class B static import yourpacage.ClassA you can call static methods without writting the class name.

Valerii Rusakov
  • 1,051
  • 2
  • 11
  • 22
0

If the two classes are in the same package you don't have to import them you can simply go:

Classname.methodName(possibleParameter);

If not in the same package import the package as mentioned by Bernhard Poiss.

Akunosh
  • 237
  • 1
  • 2
  • 10
0

i can't see how something like this can happen, unless:

  1. classB is a static inner class of classA or something of that sort.
  2. you have a static import somewhere (and that works only if you place the classes inside a package).