Download presentation
Presentation is loading. Please wait.
1
Overloaded Constructors constructors can be overloaded, like other methods – i.e., a class can define several constructors all constructors must have the same name – it's the name of the class overloaded constructors must have different parameter list if there are no constructors, Java inserts an "empty" one – e.g. Complex () {} but watch out: if there are constructors and all have parameters, then Java doesn't insert an "empty" one!
2
Calling Constructors within a Constructor a constructor can reuse what another constructor does – it can call another constructor to call it, use this(), not the constructor's name e.g. Complex() { this(0, 0); // other code } – will call Complex(double real, double imaginary – with real = 0 and imaginary = 0 constraint: – call to this() must be the first statement in the constructor's body – there can be only one call to this()
3
Static Fields and Methods what if a property doesn't belong to any specific object – typically such property belongs to all objects of a class it has the same value, e.g., a constant – it belongs to the entire category i.e. the class what if a behavior isn't logically associated with any object – typically such behavior belongs to a class – e.g. math functions, sin(x), log(x) we can use static for such fields and such methods
4
Static Fields a static field belongs to the class – has the same value for all objects all constants are static and final – static because they don't belong to any object and their value is the same for each object – final because once they have been initialized, they can't be assigned inside the class static fields are used normally – as other variables outside the class, static fields must be prefixed with the name of the class – e.g., Math.PI
5
Static Methods a static method belongs to the class – it isn't associated with any object or we can think of it as common to all objects of this class inside the class static methods are used normally – as other methods outside the class, static methods must be prefixed with the name of the class – e.g., Math.sin() the body of a static method is constrained: – can use only static fields and static methods (of the class) some utility classes have only static fields and methods – e.g. class Math in package java.lang static methods are often used to return a unique object – e.g., Mouse mouse = System.getMouse(); – then we can use their methods, e.g. mouse.getPoint();
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.