Class declaration with a method that has a parameter in Java


A class declaration can contain a method that has a parameter in Java. A program that demonstrates this is given as follows:

Example

 Live Demo

class Message {
   public void messagePrint(String msg) {
      System.out.println("The message is: " + msg);
   }
}
public class Demo {
   public static void main(String args[]) {
      Message m = new Message();
      m.messagePrint("Java is fun");
   }
}

Output

The message is: Java is fun

Now let us understand the above program.

The Message class is created with a single member function messagePrint() that has a parameter msg i.e. the message to be printed. A code snippet which demonstrates this is as follows:

class Message {
   public void messagePrint(String msg) {
      System.out.println("The message is: " + msg);
   }
}

In the main() method, an object m of class Message is created. Then messagePrint() method is called with string value "Java is fun". A code snippet which demonstrates this is as follows:

public class Demo {
   public static void main(String args[]) {
      Message m = new Message();
      m.messagePrint("Java is fun");
   }
}
raja
Published on 12-Feb-2019 15:03:31
Advertisements