We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1
IT1908
CONSTRUCTORS public Student() {
name = "No name yet."; Fundamentals age = 0; • A constructor is used in the creation of an object that is an } instance of a class using the new keyword. public Student(String name, int age) { Ex. Employee emp = new Employee(); this.name = name; o A constructor performs operations required to this.age = age; initialize the class before methods are invoked or } fields are accessed. public static void main(String[] args) { Ex. public Employee() { Student s1 = new Student(); salary = 15000; System.out.println(s1.name + ", " + s1.age); } s1.name = "Riven Reyes"; Explanation: Every Employee object created will have s1.age = 17; a default starting salary of 15000 per month. System.out.println(s1.name + ", " + s1.age); o Constructors are never inherited. Student s2 = new Student("Nika Pena", 18); o Constructor declarations use the name of the class System.out.println(s2.name + ", " s2.age); and have no return type. } • If you do not include any constructors in a class, Java provides } a default constructor, a constructor with an empty Explanation: Instances of the Student class can be created parameter list and body. This is invisibly added to the class. It with or without arguments. Student s1 = new Student(); is also known as a no-argument constructor. calls the default constructor because it does not have Ex. public Employee() { } arguments. • The this keyword is used when the instance variable has the • When a constructor calls another constructor with a greater same name with the constructor’s parameter. number of parameters, it is called constructor chaining. This Example: is accomplished using the this keyword too. The this() call public class Employee { must be the first statement in the constructor. private double salary; Example: public Employee(double salary) { public Student() { this.salary = salary; this("No name yet."); } } } public Student(String name) { this(name, 0); Constructor Overloading } • Constructor overloading occurs when constructors have public Student(String name, int age) { different type parameters. this.name = name; Example: this.age = age; public class Student { } private String name; Reference: private int age; Oracle Docs (n.d.). Citing sources. Retrieved from https://docs.oracle.com/javase/tutorial/java/javaOO/index.html