Call public class in java

Java classes and objects how to call method

If you really are in the case that you need a Class object (remember that it will just point to the Class, not to the instance you have created), you can use Java reflection: Solution 2: if method foo() returns Class, it means it don’t return actual instance of the objet on which you want to call bar() method, but the class itself, so it’s not possible to call method bar() on Class as Class.class don’t have a method bar. Instead, use the class name to call the static method: Solution 2: As the others have said, if you intend to access the method statically, you do not need an instance, and therefore you do not need a parameter in at all.

How can I Use of «Object Class» to call methods of user-defined classes in java

cast the Object (the super class) to TestClassTwo (the sub class):

String name = ((TestClassTwo) obj).getTwoName(); 
TestClassTwo temp = (TestClassTwo) obj String name = temp.getTwoName(); 

Note that using an instance to call static method is useless. Instead, use the class name to call the static method:

String name = TestClassTwo.getTwoName(); 

As the others have said, if you intend to access the method statically, you do not need an instance, and therefore you do not need a parameter in TestClass#getName at all. If you do want it to be an instance method, however, you can do one of three things:

1) Take in the type TestClassTwo in TestClass#getName :

public class TestClass < public void getName(TestClassTwo obj) throws InstantiationException, IllegalAccessException, ClassNotFoundException < String name = obj.getTwoName(); // Do something with 'name' >public static void main(String args[]) throws InstantiationException, IllegalAccessException, ClassNotFoundException < TestClass tc=new TestClass(); tc.getName(new TestClassTwo()); >> 

2) Cast the object to an instance of TestClassTwo , checking the type:

public class TestClass < public void getName(Object obj) throws InstantiationException, IllegalAccessException, ClassNotFoundException < if (obj instanceof TestClassTwo) < TestClassTwo two = (TestClassTwo) obj; String name = two.getTwoName(); // Do something with 'name' >else < // Handle failure accordingly (throw an exception, log an error, do nothing, etc.) >> public static void main(String args[]) throws InstantiationException, IllegalAccessException, ClassNotFoundException < TestClass tc=new TestClass(); tc.getName(new TestClassTwo()); >> 

3) If you want to allow other classes to have a getTwoName() function, define an interface and take an instance of that interface as a parameter to TestClass#getName :

public interface HasTwoName < public String getTwoName(); >public class TestClassTwo implements HasTwoName < @Override public String getTwoName() < return "2nd"; >> public class TestClass < public void getName(HasTwoName obj) throws InstantiationException, IllegalAccessException, ClassNotFoundException < String name = two.getTwoName(); // Do something with 'name' >public static void main(String args[]) throws InstantiationException, IllegalAccessException, ClassNotFoundException < TestClass tc=new TestClass(); tc.getName(new TestClassTwo()); >> 

Why? You don’t need to use any object, as the method is static. Using an object to call this method is futile. Just write TestClassTwo.getTwoName() .

Читайте также:  Html5 css php pdf
[I strongly suspect there is something wrong with your question.]

If you really need to access a static method of an unknown class via an object of that class, this is how you do it:

String twoName = obj.getClass().getMethod("getTwoName").invoke(null); 

Class Methods in Java, 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

JAVA Calling Object Methods

If we only need to object for one task we may call methods on anonymous objects and we see Duration: 4:16

Java Object Oriented Programming Video Tutorials

11 — Creating an object, calling a class, and constructors

In this lesson you learn how to instantiate an object, call a separate class, and create default Duration: 10:01

Invoke a method of an object of type Class

It seems like you want to group behaviors, that’s what Java interfaces do:

interface Barer < String bar(); >class Foo implements Barer < String bar() < return "I'm a Foo"; >> class Fooz implements Barer < String bar() < return "I'm a Fooz"; >> 

Then in you code you can have something like:

Barer obj; if (something) < obj = new Foo(); >else < obj = new Fooz(); >obj.bar() 

It makes little sense in fact to store the return value of a constructor in a Class object.

If you really are in the case that you need a Class object (remember that it will just point to the Class, not to the instance you have created), you can use Java reflection:

Class obj = new foo(); Method method = obj.getDeclaredMethod("bar"); method.invoke(null); 

if method foo() returns Class, it means it don’t return actual instance of the objet on which you want to call bar() method, but the class itself, so it’s not possible to call method bar() on Class as Class.class don’t have a method bar.

In your code example there is some mistake

The keyword new mean you’re creating a new instance of a class, not you’re calling a method on an object.

In fact the right approach would be to use interfaces.

Instead of returning Class from foo method, declare an interface,

public interface MyInterface

and make foo() returning MyInterface instead of Class.

MyInterface obj = tmp.foo(); obj.bar() 

If all returned values are objects of classes that implements the same method, you should declare that method in separate interface and let them implement it. Later on you can use generic wildcard like or change return type to BarInterface .

public interface BarInterface

Java : how to call methods with the same name in different objects instantiated from different classes?

I think you could program to an interface.

public interface GuiUpdate < void UpdateUI() ; >//do the same for classes that updates a gui. public class ClassA implements GuiUpdate 

Do you have control over JsonConnector? If so, inject the object references:

public JsonConnector(GuiUpdate updater) 

To add, this means you can simply do the following in a subsequent method, polymorphism and abstraction at its finest:

Читайте также:  Java обработка всех клиентов

You can create an interface , which contains the updateUI method.

Make sure that all of those objects implement that interface .

Then pass them to the JsonConnector using MyInterface instead of Object :

private CalleeInterface callingObject; public JsonConnector(CalleeInterface aCallingObject)

You can use reflection. But don’t use it if you have other solutions.

callingObject.getClass().getMethod("updateUI").invoke(callingObject); 

How To Use Classes in Java, Java Constructor Tutorial — Learn Constructors in Java · Introduction to Classes and Objects Duration: 7:20

Источник

How to call a method from another Class Java

In Java, methods/functions are nothing but a set of instructions or a block of code that will come into action when someone calls it. A method can have different instructions that work combinedly to perform a specific task. The code specified within the method will get executed only when someone calls it. In Java, methods are of two types i.e. user-defined and predefined methods.

In Java, a method can be invoked within the same class as well as from some other java class. Any method regardless of its type i.e. predefined or user-defined will be invoked/called using the dot syntax.

This post will present an in-depth overview of how to invoke a java method from another class with the help of examples. So, let’s get started!

Invoking a Java method from another class

We have to create the object of a class(class to be invoked) to invoke a method of one class in some other java class.

Let’s consider an example to understand how to invoke a method from another Java class:

  • Let’s say we have two classes i.e. “FirstClass” and “SecondClass”.
  • We assume that the “FirstClass” has a method named “Hello()” and we have to invoke it in the “SecondClass”.
  • To do that, first, we need to create an object of “FirstClass” in the main method of the “SecondClass”.
  • Once an object of the “FirstClass” is created, then we can invoke any method or attribute of the “FirstClass” within the “SecondClass” using that object.

Calling a public method from another class

We all know that programming languages have some access modifiers that define the scope/accessibility of a method, constructor, or class. “public” is one of them that is accessible inside as well as outside of a class/package.

Example: invoke a public method from some other class
In this program, we will create two classes “FirstClass” and “SecondClass” as shown in the below-given code blocks:

class FirstClass {
public void printMessage ( ) {
System. out . println ( «Welcome to linuxhint.com» ) ;
}
}

In the “FirstClass”, we created a method named “printMessage()” which will show a message “welcome to linuxhint.com” whenever someone invokes it.

Читайте также:  Java алгоритм шеннона фано

SecondClass

public class SecondClass {
public static void main ( String [ ] args ) {
FirstClass classObj = new FirstClass ( ) ;
classObj. printMessage ( ) ;
}
}

The “SecondClass” served the below-listed functionalities:

  • Created an object of the “FirstClass” using a new Keyword.
  • Invoked the “printMessage()” method using the object of the “FirstClass”.

The output proved that the “printMessage()” method of the “FirstClass” was successfully invoked from the “SecondClass”.

Calling a protected method from another Java class

In java, if a method of a class is declared with the “protected” keyword, then it can be accessed by any other class of the same package. A method declared with the protected keyword can’t be accessed out of the package directly. However, it can be accessed outside the package with the help of inheritance.

Example: how to invoke a protected method from some other class of the same package
In the following program, we will create two classes “FirstClass” and “SecondClass”:

class FirstClass {
protected void printDomainName ( ) {
System. out . println ( «Linuxhint.com» ) ;
}
}

Within FirstClass, we created a method named “printDomainName()” with the protected access modifier.

SecondClass:

Within the second class, firstly, we created an object of the “SecondClass”. Afterwards, we utilized that object to invoke the “printDomainName()” method of the FirstClass.

The above snippet verifies that we can call the protected method from some other class of the same package.

Calling a static method from another class

In Java, there is no need to create the object of a class while working with the static methods. A static method of one class can be invoked from some other class using the class name.

Example: How to invoke a static method from another class?

class FirstClass {
static void printDomain ( ) {
System. out . println ( «this is linuxhint.com» ) ;
}
}

public class SecondClass {
public static void main ( String [ ] args ) {
FirstClass. printDomain ( ) ;
}
}

In this example program, we created two classes “FirstClass” and “SecondClass”. We invoked the static method of the “FirstClass” from the main method of the “SecondClass”. Consequently, we will get the following output:

The output verified that the static method of one class can be accessed/invoked from another class directly with the class name.

Conclusion

In Java, a method can be invoked from another class based on its access modifier. For example, a method created with a public modifier can be called from inside as well as outside of a class/package. The protected method can be invoked from another class using inheritance. A static method of one class can be invoked from some other class using the class name. This write-up considered multiple examples to explain how to call a method from another class in Java.

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.

Источник

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