ADVERTISEMENT
ADVERTISEMENT

Java program to call a method using the anonymous object

Learn how to call a method using the anonymous object in Java?
Submitted by Nidhi, on March 25, 2022

Problem Solution:

In this program, we will create a class with a method and constructor. Then we will create an anonymous object and call the constructor and its method.

An object which has no reference variable is called an anonymous object.

Program/Source Code:

The source code to call a method using an anonymous object is given below. The given program is compiled and executed successfully.

// Java program to call a method using 
// an anonymous object

class Sample {
  void sayHello() {
    System.out.println("Hello World");
  }

  Sample() {
    System.out.println("Constructor called");
  }

}
public class Main {
  public static void main(String[] args) {
    new Sample().sayHello();
  }
}

Output:

Constructor called
Hello World

Explanation:

In the above program, we created two classes Sample and Main. The Sample class contains a constructor and sayHello() method.

The Main class contains a method main(). The main() method is the entry point for the program, here we created an anonymous object of the Sample class and called constructor and sayHello() method and printed messages.

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.