JAVATM- The Beginnings

Static Fields and Methods

Suppose you wrote a Name class which stores a person’s name:

public class Name

{

                 private String name;

                 public Name(String s)

                 {

                          name = s;

                 }

                 public String getName()

               {

                      return name;

                 }

}

Let’s say you wanted to create a comma separated list of all Name objects in the order you create them. You would have to call the getName method of each Name object and interleave with commas. It would also be your responsibility to get the order right.

            public static void main(String[] args)

            {

                    Name name1 = new Name("George");

                       Name name2 = new Name("Martha");

                    Name name3 = new Name("Abe");

                   Name name4 = new Name("Mary");

                    Name name5 = new Name("James");

                    Name name6 = new Name("Dolly");

                   System.out.println(name1.getName() + ","

                                          + name2.getName() + ","

                                          + name3.getName() + ","

                                          + name4.getName() + ","

                                          + name6.getName() + ","                        // Oops

                                          + name5.getName()        );                // Oops

             }

In the above program, the order of the last two Name objects is switched, and the program incorrectly prints out the following:

Copyright ©2017 by Ralph Lecessi Incorporated. All rights reserved.



Back to ralphlecessi.com