ADVERTISEMENT
ADVERTISEMENT

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 »


ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.