Lesson 2 | Creating objects from classes |
Objective | Create objects from classes. |
Creating Objects from Classes in Java
How is Memory Management implemented in Java?
Programmers new to Java are often puzzled by the fact that memory management is handled automatically. Most other programming languages such as C and C++ place the responsibility of memory management in the hands of programmers. Managing memory by hand in C/C++ certainly gives you more flexibility, but it comes at the cost of memory leaks. When memory is allocated and then accidentally forgotten, it is effectively lost to the system, which is a very bad thing.
Java solves the memory leak problem by taking complete charge of memory management. When you create an object from a class using the new operator, the memory for the object is allocated and managed by Java. When you are later finished with the object, Java frees up the memory automatically. The miracle of Java's memory management has to do with a process known as garbage collection. Garbage collection is when Java periodically looks for objects that are no longer being used so that it can free the memory associated with them. Even a programming language as clean as Java has to clean house from time to time.
Ojbect Creation in Java
When you create an object from a class it is known as an instance of the class. This process of creating an instance of an object is referred to as instantiating an object. The creation of an object always begins with a constructor, which is a special method that is called when an object is first created. Constructors have the same name as the class to which they belong, and are a good place to perform any initialization required of the class. If you do not provide a constructor for your class, Java will provide a default constructor for you. The default constructor has no arguments and does not perform any initialization.
The primary means of creating objects in Java is the new
operator. In the following example, an instance of class Circle
is created, the instance variable radius
is set to 5.0
, and then the instance method area()
is invoked to display the area of the circle. Because no constructors were provided in the Circle
class, the Java-provided default constructor was used.
class Circle {
double radius;
double area() {
return Math.PI * radius * radius;
}
}
class CircleTest {
public static void main(String[] args) {
Circle c = new Circle();
c.radius = 5.0;
System.out.println(c.area());
}
}
Instance Variables Methods - Exercise