📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
1. Calling a Non-Static Method
Example
Let's consider a simple example with two classes: Greeting and MainApp.Greeting.java
public class Greeting {
public void sayHello(String name) {
System.out.println("Hello, " + name + "!");
}
}
MainApp.javapublic class MainApp {
public static void main(String[] args) {
Greeting greeting = new Greeting(); // Creating an instance of Greeting
greeting.sayHello("Java Learner"); // Calling the non-static method
}
}
Output:
Hello, Java Learner!In this example, the sayHello method is a non-static method inside the Greeting class. To call this method, the MainApp class first creates an instance of Greeting using new Greeting() and then calls the method on that instance.
2. Calling a Static Method
Example
public class Greeting {
public static void sayStaticHello(String name) {
System.out.println("Static Hello, " + name + "!");
}
}
MainApp.javapublic class MainApp {
public static void main(String[] args) {
Greeting.sayStaticHello("Static Java Learner"); // Calling the static method
}
}
Output:
Static Hello, Static Java Learner!In this case, sayStaticHello is a static method. We call it directly on the class (Greeting.sayStaticHello) without needing to create an instance of Greeting.
Comments
Post a Comment
Leave Comment