Monday, December 5, 2011

Class Definition » New

Creating Objects
  1. Using the new keyword.
  2. new is always followed by the constructor of the class.
For example, to create an Employee object, you write:
Employee employee = new Employee();
Here, 'employee' is an object reference of type Employee.
  1. Once you have an object, you can call its methods and access its fields, by using the object reference.
  2. You use a period (.) to call a method or a field.
For example:
objectReference.methodName
objectReference.fieldName
The following code, for instance, creates an Employee object and assigns values to its age and salary fields:
public class MainClass {

  public static void main(String[] args) {
    Employee employee = new Employee();
    employee.age = 24;
    employee.salary = 50000;
  }

}

class Employee {
    public int age;
    public double salary;
    public Employee() {
    }
    public Employee(int ageValue, double salaryValue) {
        age = ageValue;
        salary = salaryValue;
    }
}
When an object is created, the JVM also performs initialization that assign default values to fields.

 Memory Leak Demo
class List {
  MemoryLeak mem;
  List next;
}

class MemoryLeak {
  static List top;

  char[] memory = new char[100000];

  public static void main(String[] args) {
    for (int i = 0; i < 100000; i++) {
      List temp = new List();
      temp.mem = new MemoryLeak();
      temp.next = top;
      top = temp;
    }
  }
}
 
http://www.java2s.com/Tutorial/Java/0100__Class-Definition
/Catalog0100__Class-Definition.htm

No comments:

Post a Comment