2. Guarantees initialization of every object Essentially a method Called when an object is created, even when no reference exists The name of the constructor is the same as the name of the class Unusual type of method because it has no return value the new expression does return a reference to the newly created object public class Shape { public Shape() {} } Shape s = new Shape() Constructor
3. A constructor that takes no arguments is called the default constructor If you provide no constructor the default constructor is provided by default by the compiler. You can definitely have constructors with one or more arguments public class Rectangle{ private int length; private int breadth; public Rectangle(int length, int breadth) { length = length; breadth = breadth; } } Default Constructor
4. Method overloading allow the same method name to be used with different argument types. Constructors are methods and they can be overloaded too. Method overloading
5. public class Tree { int height; public Tree() { print("Planting a seedling"); height = 0; } public Tree(intinitialHeight) { height = initialHeight; print("Creating new Tree that is " + height + " feet tall"); } public void info() { print("Tree is " + height + " feet tall"); } public void info(String s) { print(s + ": Tree is " + height + " feet tall"); } } Overloading in Action
6. Test the Tree class by invoking each constructor and each method Exercise
7. Each overloaded method must take a unique list of argument types Even differences in the ordering of arguments are sufficient to distinguish two methods, although you don’t normally want to take this approach because it produces difficult-to-maintain code Distinguishing overloaded method
8. public class OverloadingOrder { static void f(String s, inti) { print("String: " + s + ", int: " + i); } static void f(inti, String s) { print("int: " + i + ", String: " + s); } public static void main(String[] args) { f("String first", 11); f(99, "Int first"); } } Overloading in Action
9. void f() {} int f() { return 1; } int x = f(); f(); You cannot use return value types to distinguish Overloading on return value
10. Reference of the current object that is available to no static methods Used widely in constructors to avoid ambiguity Use if you want to pass a reference of current object to another object. this
11. There is no destructor in Java Memory is managed automatically by a garbage collector which is part of JVM A JVM may not even have a garbage collector When garbage collector runs is not under programmers control System.gc() – just a hint Common garbage collection technique Mark and Sweep finalization() Called before an object is garbage collected Useless method, should be avoided as you never know when it will be called Use in JNI programs – malloc() , free() Destruction