0

Difference between an instance variable and parameter with respect to a constructor

Difference between an instance variable and parameter with respect to a constructor

17th Nov 2018, 12:01 AM
onwuazombe tobechukwu
onwuazombe tobechukwu - avatar
1 Answer
+ 6
Constructor allows instance variable initialization as the instance is created, the difference is obvious, instance variable is declared within the class, as a member. While the constructor parameters only valid within the constructor scope, they are used temporarily, just to initialize the instance variable values. See this class constructor, now, the instance variable are named <name> and <age>, and so are the parameters, so there we use "this.name" to refer to the instance variable <name>, to be strictly clear which is what, because they share the same name. I hope I understood your question correctly. class Student { private String name; private int age; Student(String name, int age) { this.name = name; this.age = age; } void Intro() { System.out.println("Hello, my name is " + name + ". I am " + age + " years old."); } } public class Demo { public static void main(String[] args) { Student Albert = new Student("Albert", 11); Albert.Intro(); } } Hth, cmiiw
18th Nov 2018, 4:42 AM
Ipang