📘 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.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides 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