Java program to print message using class

This java program will print message using class method - here, we will print the message by using same class method and other class method.

In this example we will print a message on screen by creating a class. We will make a separate class in which there is a method named printMessage to print the message. We will create a object of that class in public class in which Main() function is called. Using that object we will call that method and output will be on screen.

Creating method in same class (public class) in which main method exists:

// Creating method in same class (public class)
// in which main method exists.

import java.util.*;

class HelloWorld {
  public void dispMessage() {
    System.out.println("Hello World.");
  }

  //Main method
  public static void main(String s[]) {
    //creat object of HelloWorld Class
    HelloWorld obj = new HelloWorld();
    obj.dispMessage();
  }
}

Output

Compile: javac HelloWorld.java 
Run: java HelloWorld 

Output: Hello World.

Creating method in other (external) class:

// Creating method in other (external) class

import java.util.*;

//class to print message
class ShowMessage {
  public void dispMessage() {
    System.out.println("Hello World.");
  }
}

//public class
public class HelloWorld {
  //main method
  public static void main(String[] s) {
    //create object of ShowMessage class.
    ShowMessage obj = new ShowMessage();
    obj.dispMessage();
  }
}

Output

Compile: javac HelloWorld.java 
Run: java HelloWorld 

Output: Hello World.

Java Class and Object Programs »



Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.