Java Creating an Object

Java Creating an Object

In Java, you can create an object of a class by using the new operator and calling the class's constructor.

Here is an example of how to create an object in Java:

public class Main {
  public static void main(String[] args) {
    // Create an object of the Person class
    Person person = new Person("John", 30);

    // Print the object's fields
    System.out.println(person.name);  // Output: John
    System.out.println(person.age);   // Output: 30
  }
}

class Person {
  String name;
  int age;

  // Constructor
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }
}
Source:w‮l.ww‬autturi.com

In this example, we have a Person class with two fields: name and age. The Person class has a constructor that takes two arguments: name and age.

To create an object of the Person class, we use the new operator and call the constructor with the required arguments. This creates a new Person object and assigns it to the person variable.

We can then access the object's fields using the dot notation (e.g., person.name).

Note that in Java, it is good practice to make the fields of a class private and provide getter and setter methods for accessing and modifying the fields. This allows you to control how the fields are accessed and modified, and helps to ensure the integrity of the data in the object. Here is an example:

public class Main {
  public static void main(String[] args) {
    // Create an object of the Person class
    Person person = new Person("John", 30);

    // Print the object's fields
    System.out.println(person.getName());  // Output: John
    System.out.println(person.getAge());   // Output: 30

    // Set the object's fields
    person.setName("Jane");
    person.setAge(32);

    // Print the object's fields
    System.out.println(person.getName());  // Output: Jane
    System.out.println(person.getAge());   // Output: 32
  }
}

class Person {
  private String name;
  private int age;

  // Constructor
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }

  // Getter and setter methods
  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }
}

In this example, we have added getter and setter methods for the name and age fields. We use the getter methods (getName and getAge) to access the fields, and the setter methods (setName and setAge) to modify the fields. This allows us to control how the fields are accessed and modified, and helps to ensure the integrity of the data in the object.

Created Time:2017-11-03 00:14:40  Author:lautturi