Access class method java

How can i access an object from another method in java?

I have the object numberlist that i created in create() method and i want to access it so i can use it in the question() method. Is there another way to do this that I probably missed? Am I messing something up? If not, how should I do this to get the same functionality as below?

private static void create() < Scanner input = new Scanner(System.in); int length,offset; System.out.print("Input the size of the numbers : "); length = input.nextInt(); System.out.print("Input the Offset : "); offset = input.nextInt(); NumberList numberlist= new NumberList(length, offset); >private static void question()< Scanner input = new Scanner(System.in); System.out.print("Please enter a command or type ?: "); String c = input.nextLine(); if (c.equals("a"))< create(); >else if(c.equals("b"))< numberlist.flip(); \\ error >else if(c.equals("c"))< numberlist.shuffle(); \\ error >else if(c.equals("d")) < numberlist.printInfo(); \\ error >> 

3 Answers 3

While interesting, both of the answers listed ignored that fact that the questioner is using static methods. Thus, any class or member variable will not be accessible to the method unless they are also declared static, or referenced statically. This example:

public class MyClass < public static String xThing; private static void makeThing() < String thing = "thing"; xThing = thing; System.out.println(thing); >private static void makeOtherThing() < String otherThing = "otherThing"; System.out.println(otherThing); System.out.println(xThing); >public static void main(String args[]) < makeThing(); makeOtherThing(); >> 

Will work, however, it would be better if it was more like this.

public class MyClass < private String xThing; public void makeThing() < String thing = "thing"; xThing = thing; System.out.println(thing); >public void makeOtherThing() < String otherThing = "otherThing"; System.out.println(otherThing); System.out.println(xThing); >public static void main(String args[]) < MyClass myObject = new MyClass(); myObject.makeThing(); myObject.makeOtherThing(); >> 

Источник

Java Class Methods

You learned from the Java Methods chapter that methods are declared within a class, and that they are used to perform certain actions:

Example

Create a method named myMethod() in Main:

myMethod() prints a text (the action), when it is called. To call a method, write the method’s name followed by two parentheses () and a semicolon;

Example

Inside main , call myMethod() :

public class Main < static void myMethod() < System.out.println("Hello World!"); >public static void main(String[] args) < myMethod(); >> // Outputs "Hello World!" 

public class MyClass <
static void myMethod(int x) <
System.out.println(x);
>

public static void main(String[] args) myMethod(10);
>
>

Static vs. Public

You will often see Java programs that have either static or public attributes and methods.

In the example above, we created a static method, which means that it can be accessed without creating an object of the class, unlike public , which can only be accessed by objects:

Example

An example to demonstrate the differences between static and public methods:

public class Main < // Static method static void myStaticMethod() < System.out.println("Static methods can be called without creating objects"); >// Public method public void myPublicMethod() < System.out.println("Public methods must be called by creating objects"); >// Main method public static void main(String[] args) < myStaticMethod(); // Call the static method // myPublicMethod(); This would compile an error Main myObj = new Main(); // Create an object of Main myObj.myPublicMethod(); // Call the public method on the object >> 

Note: You will learn more about these keywords (called modifiers) in the Java Modifiers chapter.

Access Methods With an Object

Example

Create a Car object named myCar . Call the fullThrottle() and speed() methods on the myCar object, and run the program:

// Create a Main class public class Main < // Create a fullThrottle() method public void fullThrottle() < System.out.println("The car is going as fast as it can!"); >// Create a speed() method and add a parameter public void speed(int maxSpeed) < System.out.println("Max speed is: " + maxSpeed); >// Inside main, call the methods on the myCar object public static void main(String[] args) < Main myCar = new Main(); // Create a myCar object myCar.fullThrottle(); // Call the fullThrottle() method myCar.speed(200); // Call the speed() method >> // The car is going as fast as it can! // Max speed is: 200 

Example explained

1) We created a custom Main class with the class keyword.

Читайте также:  Добавление картинок php mysql

2) We created the fullThrottle() and speed() methods in the Main class.

3) The fullThrottle() method and the speed() method will print out some text, when they are called.

4) The speed() method accepts an int parameter called maxSpeed — we will use this in 8).

5) In order to use the Main class and its methods, we need to create an object of the Main Class.

6) Then, go to the main() method, which you know by now is a built-in Java method that runs your program (any code inside main is executed).

7) By using the new keyword we created an object with the name myCar .

8) Then, we call the fullThrottle() and speed() methods on the myCar object, and run the program using the name of the object ( myCar ), followed by a dot ( . ), followed by the name of the method ( fullThrottle(); and speed(200); ). Notice that we add an int parameter of 200 inside the speed() method.

Remember that..

The dot ( . ) is used to access the object’s attributes and methods.

To call a method in Java, write the method name followed by a set of parentheses (), followed by a semicolon ( ; ).

A class must have a matching filename ( Main and Main.java).

Using Multiple Classes

Like we specified in the Classes chapter, it is a good practice to create an object of a class and access it in another class.

Remember that the name of the java file should match the class name. In this example, we have created two files in the same directory:

Main.java

public class Main < public void fullThrottle() < System.out.println("The car is going as fast as it can!"); >public void speed(int maxSpeed) < System.out.println("Max speed is: " + maxSpeed); >> 

Second.java

When both files have been compiled:

Источник

Class Methods in Java | Explained

In Java, a method is nothing but a block of code/statement that is declared within the class and can perform different actions when someone calls it. Some methods can be called directly with their name (i.e. without creating the class object) while some methods require instance/object of the class (i.e. must be invoked with the object of the class).

The methods that can be called directly are referred as a class or static methods, while the methods that need an object of the class to be invoked are referred as instance or non-static methods.

This write-up will present a detailed overview of class methods and in this regard, it will cover the following aspects of Java class methods:

Class Method in Java

Generally, when we have a class then we have to create an object of that class to access its methods and other members. However, the class/static methods can be accessed inside of the class without creating an instance of that class.

How to Access Class Methods

Let’s consider the below-given example to understand how to create and access a static/class method in Java.

Читайте также:  Css v34 source серверы

The below code snippet takes two numbers from the user and perform addition on them:

public static int addition ( int num1, int num2 ) {
int add = num1 + num2 ;
return add ;
}

public static void main ( String [ ] args ) {

int number1, number2, sum ;
Scanner scan = new Scanner ( System . in ) ;
System . out . print ( «Enter 1st number: » ) ;
number1 = scan. nextInt ( ) ;
System . out . print ( «Enter 2nd number: » ) ;
number2 = scan. nextInt ( ) ;
sum = addition ( number1, number2 ) ;
System . out . println ( «Sum = » + sum ) ;
}
}

The complete code and its respective output will be something like this:

From the above output, it is clear that there is no need to create the object of the class to call a static method instead it can be accessed directly within the class.

How to Access Public Methods

Now let’s consider the below example to test whether a public method can be accessed directly or not:

public int addition ( int num1, int num2 ) {
int add = num1 + num2 ;
return add ;
}

public static void main ( String [ ] args ) {

int number1, number2, sum ;
Scanner scan = new Scanner ( System . in ) ;
System . out . print ( «Enter 1st number: » ) ;
number1 = scan. nextInt ( ) ;
System . out . print ( «Enter 2nd number: » ) ;
number2 = scan. nextInt ( ) ;
sum = addition ( number1, number2 ) ;
System . out . println ( «Sum = » + sum ) ;
}
}

All the code is the same as in the previous example except the access modifier, but this time we get an error as shown in the following code snippet:

To access a non-static function, first, we have to create the object of the class then we will be able to access the method of the class:

The above snippet verifies that when we call the non-static method with the help of a class object then it works appropriately and provides the error-free output.

How to Access a Method from a Different Class

We have seen that a static method doesn’t require any object to be called within the same class but what will happen when we have multiple classes? Will the static method be invoked directly in such a case? Let’s experiment with it!

Let’s consider we have two class: one class named “AddNumbers” which will hold the main method and the second one is “MyFunctions” class:

MyFunctions.java

package addnumbers ;
public class MyFunctions {

public static int addition ( int num1, int num2 ) {
int add = num1 + num2 ;
return add ;
}
}

AddNumbers.java

public static void main ( String [ ] args ) {
int number1, number2, sum ;
Scanner scan = new Scanner ( System . in ) ;
System . out . print ( «Enter 1st number: » ) ;
number1 = scan. nextInt ( ) ;
System . out . print ( «Enter 2nd number: » ) ;
number2 = scan. nextInt ( ) ;
sum = addition ( number1, number2 ) ;
System . out . println ( «Sum = » + sum ) ;
}
}

We call the addition function of the MyFunctions class from the main method of AddNumbers class:

Although the addition method is static but we still get an error when we try to access it directly. This is because the addition method is not in the same class. So, to access the method of some other class we have to create the object of that class irrespective of its access modifier i.e. static or public.

AddNumbers.java

public class AddNumbers {
public static void main ( String [ ] args ) {
int number1, number2, sum ;
Scanner scan = new Scanner ( System . in ) ;
System . out . print ( «Enter 1st number: » ) ;
number1 = scan. nextInt ( ) ;
System . out . print ( «Enter 2nd number: » ) ;
number2 = scan. nextInt ( ) ;
MyFunctions obj = new MyFunctions ( ) ;
sum = obj. addition ( number1, number2 ) ;
System . out . println ( «Sum = » + sum ) ;
}
}

This time we create the object of MyFunctions class in the main function of AddNumbers class and then we access the addition method with the help of that object:

Читайте также:  Python selenium disable image loading

Now the above snippet verifies that the error has gone, and with the help of the object of MyFunctions class we got the desired results.

Conclusion

The class/static method can be accessed within the class directly while accessing the public methods without creating the object is not possible. While, in the case of multiple classes, the methods will be accessible only with the help of class objects regardless of their access modifier. This write-up provides a comprehensive guide of what are class methods and how to access them from the same class and from a different class.

About the author

Anees Asghar

I am a self-motivated IT professional having more than one year of industry experience in technical writing. I am passionate about writing on the topics related to web development.

Источник

How to access a static method via a class reference

It is only possible to access those methods using reflection. You cannot reference a class directly, only an instance of type Class.

To use reflection to invoke methodname(int a, String b):

Method m = clazz.getMethod("methodname", Integer.class, String.class); m.invoke(null, 1, "Hello World!"); 

You may want to think about your design again, to avoid the need to dynamically call static methods.

You can invoke a static method via reflection like this :

Method method = clazz.getMethod("methodname", argstype); Object o = method.invoke(null, args); 

Where argstype is an array of arguments type and args is an array of parameters for the call. More informations on the following links :

In your case, something like this should work :

Method method = clazz.getMethod("foo", null); method.invoke(null, null); // foo returns nothing 

You can leave the last null s in the last two lines away, as those methods are now declared as var-args methods.

You cannot access static methods without an explicit reference to the class.

No inheritance here, sorry, so you must either do:

If you really need it, you will have to do a check:

Object o = . // eith an A or B instance. if( o instanceof A ) < A.foo() >else

But why don’t you just make those functions instance functions, and let them implement an interface?

Okey, you have a class object. Then do:

Class c = . ; c.getMethod("foo").invoke(null); // null to invoke static methods 

I had the logic originally written for interfaces and my derived classes (‘A’ or ‘B’) cannot be instantiated since they were defined as inner classes and didn’t have a public class identifier, hence I had to resort to this technique.

@user339108 interfaces are the way to proceed here, just make sure A and B are not inner classes.

Interfaces can’t declare static methods. And for the last part, it’s better explained in at least two answers

According to my lack of knowledge the need for the requested construct is given by the fact that an interface doesn’t offer the possibility of static abstract methods. Here is an example:

public enum Cheese implements Yumy < GOUDA(49), ESROM(40), HWARTI(38); private int percentage; private Cheese(int fat100) constructor public void yamyam() // as in Yumy public static Cheese getByFat(int fat100) // no chance to be part of interface >; 

I hope this isn’t making too many assumptions or deviating too far from your question, but if your two classes share a common supertype and creating an instance is tolerable then you can:

  1. Implement a common interface
  2. Create an instance of the object via myClass.newInstance() (class must have an empty constructor)
  3. Call the static method from the instance object.
interface Foo < void foo(); >class A implements Foo class B implements Foo  public void something(Class clazz) < T myInstance = clazz.newInstance(); myInstance.foo(); >. something(A.class); 

It’s a little bizarre but in my case it proved to be useful, and I began by asking the very same question that you did.

Источник

Оцените статью