main Method in Java
All Java code is structured into classes and these give rise to objects when a program is run. So the methods of an object must be invoked by some code in another object (or even a method in the same object). This just leads to the further question of how this object gets created, and so on, indefinitely. Clearly, there must be a starting point for the whole business of creating objects and invoking their methods. In Java, this is the role of the main method. Let us now see how we can use a main method to test the Robot class.First, we need to define a class that can be used to carry out the testing - let us call it
TestRobot. This class will have a main method, defined in the way we saw earlier, as follows:
public class TestRobot
{
public static void main (String []args)
{
...
All main methods are declared in this way.
When we run a compiled program made up of the classes Robot and TestRobot,the Java system starts at the main method and follows the Java instructions there. In this case we need to test some robots, so we must create one or more robots and then invoke their methods:
public class TestRobot
{
public static void main (String []args)
{
// declare variables to reference Robots
Robot artoo;
Robot deetoo;
// create two Robot objects
artoo = new Robo t(); // default starting position (1, 1)
deetoo = new Robot(2, 5); // initially at x = 2, y = 5
// move the Robot named artoo one position East
artoo.moveEast();
// move the Robot named deetoo
// one position West and then one position North
deetoo.moveWest();
deetoo.moveNorth();
}
}
It would actually be possible to put this main method into the class Robot, rather than creating a new TestRobot class. However, this is not normally good practice. It is better for the Robot class to be more general purpose, so it could potentially be used in lots of different programs. Keeping the main method separate makes the Robot class more flexible.
Java Assignment Help - Java Homework Help
Struggling with java programming language? Are you not finding solution for your main method in Java homework and assignments? Live main method in Java experts are working for students by solving their doubts & questions during their course studies and training program. We at Expertsmind.com offer main method in Java homework help, java assignment help and main method in Java projects help anytime from anywhere for 24x7 hours. Computer science programming assignments help making life easy for students.
Why Expertsmind for assignment help
- Higher degree holder and experienced experts network
- Punctuality and responsibility of work
- Quality solution with 100% plagiarism free answers
- Time on Delivery
- Privacy of information and details
- Excellence in solving java programming language queries in excels and word format.
- Best tutoring assistance 24x7 hours