Professional Documents
Culture Documents
- is used in the creation of an object that is an instance of a class using the new keyword
Example:
o A constructor performs operations required to initialize the class before methods are
invoked or fields are accessed
Example:
Explanation: Every Employee object created will have a default starting salary of
15000 per month.
o Constructors are never inherited
o Constructor declarations use the name of the class and have no return type
• default constructor
- a constructor with an empty parameter list and body
- This is invisibly added to the class
- also known as a no-argument constructor
Example:
public Employee() { }
• this
- is used when the instance variable has the same name with the constructor’s parameter
Example:
}
• Constructor overloading
- occurs when constructors have different type parameters
Example:
public class Student {
private String name;
private int age;
public Student() {
name = "No name yet."; age = 0;
}
Explanation:
Instances of the Student class can be created with or without arguments. Student s1 =
new Student(); calls the default constructor because it does not have arguments
• constructor chaining
- calls another constructor with a greater number of parameters
- accomplished using the this keyword too
- this() call must be the first statement in the constructor
Example:
public Student() { this("No name yet.");
}
Example:
}
Rules in Implementing Encapsulation
2. Names of getter methods begin with get if the property is not a Boolean
Example:
public String getName() {
return name;
}
• Immutable
- if it remains unchanged after an object of another class is constructed
• For a class to be immutable
- remove the setter methods and use the constructor for setting the values
Example:
public class Student {
private String name;
public Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
• Inheritance
- allows a class to acquire all the attributes (fields) and behaviors (methods) of another class
• Object
- Where all classes in java inherit from