In Java, you have to declare new objects and then create them with the new operator. For example, here's how I create an object of the Java String class, passing the text "Welcome to Java" to that class's constructor: public class ch10_12 { public static void main(String[] args) { String greeting1; greeting1 = new String("Welcome to Java"); . . . Note that I first declared the greeting1 object, giving the object's class, String , as its type. Then I create the object with the new operator. Overloaded ConstructorsClasses can have different constructors that handle different types of data. For example, I passed a string to the String class's constructor in the previous example, but I can also pass an array of characters this way: public class ch10_12 { public static void main(String[] args) { String greeting1, greeting2, greeting3; greeting1 = new String("Welcome to Java"); char characters[] = {'W', 'e', 'l', 'c', 'o', 'm', 'e', ' ', 't', 'o', ' ', 'J', 'a', 'v', 'a'}; greeting2 = new String(characters); . . . } } Constructors and methods that can take different argument lists are said to be overloaded.
Assigning ObjectsYou can also assign one object to another using the = assignment operator: public class ch10_12 { public static void main(String[] args) { String greeting1, greeting2, greeting3; greeting1 = new String("Welcome to Java"); char characters[] = {'W', 'e', 'l', 'c', 'o', 'm', 'e', ' ', 't', 'o', ' ', 'J', 'a', 'v', 'a'}; greeting2 = new String(characters); greeting3 = greeting2; . . . } } To end this example, I'll print all the strings we've created: Listing ch10_12.javapublic class ch10_12 { public static void main(String[] args) { String greeting1, greeting2, greeting3; greeting1 = new String("Welcome to Java"); char characters[] = {'W', 'e', 'l', 'c', 'o', 'm', 'e', ' ', 't', 'o', ' ', 'J', 'a', 'v', 'a'}; greeting2 = new String(characters); greeting3 = greeting2; System.out.println(greeting1); System.out.println(greeting2); System.out.println(greeting3); } } Here's what this application looks like when run: %java ch10_12 Welcome to Java Welcome to Java Welcome to Java That's how to declare and create objects in Java. It's similar to the way you declare and create simple variables , with the added power of configuring objects by passing data to a class's constructor. |