Declaring and Creating Objects

In Java, you must declare new objects, then you 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 app
{
    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.

Overloading Constructors

Classes 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, which is useful if my data is stored as such an array:

public class app
{
    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 called overloaded.

To overload a constructor or method, you just define it a number of times, each with a different argument list.

Assigning Objects

You can also assign one object to another, using the = assignment operator:

public class app
{
    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 out all the strings that we've created:

public class app
{
    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 app
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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.99.7