Which is the special method in which class name and method name should be same?
You learned from the Java Methods chapter that methods are declared within a class, and that they are used to perform certain actions: Show ExampleCreate a method named
ExampleInside
Try it Yourself » Static vs. PublicYou will often see Java programs that have either 0 or 1 attributes and methods.In the example above, we created a 0 method, which means that it can be accessed without creating an object of the class, unlike 1, which can only be accessed by objects:ExampleAn example to demonstrate the differences between 0 and 1 methods:
Try it Yourself » Note: You will learn more about these keywords (called modifiers) in the Java Modifiers chapter. Access Methods With an ObjectExampleCreate a Car object named 6. Call the 7 and 8 methods on the 6 object, and run the program:
Try it Yourself » Example explained1) We created a custom 0 class with the 1 keyword.2) We created the 7 and 8 methods in the 0 class.3) The 7 method and the 8 method will print out some text, when they are called.4) The 8 method accepts an 8 parameter called 9 - we will use this in 8).5) In order to use the 0 class and its methods, we need to create an object of the 0 Class.6) Then, go to the 2 method, which you know by now is a built-in Java method that runs your program (any code inside main is executed).7) By using the 3 keyword we created an object with the name 6.8) Then, we call the 7 and 8 methods on the 6 object, and run the program using the name of the object ( 6), followed by a dot ( 9), followed by the name of the method ( 0 and 1). Notice that we add an 8 parameter of 200 inside the 8 method.Remember that..The dot ( 9) is used to access the object's attributes and methods.To call a method in Java, write the method name followed by a set of parentheses (), followed by a semicolon ( 5).A class must have a matching filename ( 0 and Main.java).Using Multiple ClassesLike we specified in the Classes chapter, it is a good practice to create an object of a class and access it in another class. Remember that the name of the java file should match the class name. In this example, we have created two files in the same directory: Can a class name and method name be same?Yes, It is allowed to define a method with the same name as that of a class. There is no compile-time or runtime error will occur.
Which special method of a class has the same name as that of its class?Explanation: A constructor is a method that initializes an object immediately upon creation. It has the same name as that of class in which it resides.
Can two classes have method with same name?Yes, we can define multiple methods in a class with the same name but with different types of parameters.
|