How to call a class from another class in Java?
Hello everyone!
In this tutorial, we shall learn about how to call a class from another class in Java.
Java Program to call a class from another class
class Class1 { void display() { System.out.println("Inside Class1"); } } public class Class2 { public static void main(String[] args) { System.out.println("Inside Class2"); Class1 obj1=new Class1(); obj1.display(); } }
Explanation
We create 2 classes Class1 and Class 2. Since the main written is written inside Class2, the file name should be saved as Class2.java.
Class1 contains a display()
function which prints “Inside Class1”.
Inside Class2, we have the main method. After printing “Inside Class2”, an object obj1 of Class1 is created. This object is then used to call the display function of Class1.
Output
Inside Class2 Inside Class1
Leave a Reply