Académique Documents
Professionnel Documents
Culture Documents
println(Age=+age); } } class Test { Public static void main(String args[]) { Info person=new Info(); person.displayInfo(); } }
class Info { String Name; Int age; Void displayInfo() { System.out.println(Name=+name); System.out.println(Age=+age); } } class Test { Public static void main(String args[]) { Info person=new Info(); person.name=Ram; person.age=25; person.displayInfo(); } }
class Info { String Name=Mohit; Int age=30; Void displayInfo() { System.out.println(Name=+name); System.out.println(Age=+age); } } class Test { Public static void main(String args[]) { Info person=new Info(); person.name=Ram; person.age=25; person.displayInfo(); }}
Protection of data is always needed. So we need to specify the access specifiers for the data. In java these are of 4 types.
If the instance variables of Info class are declared as private, then they are not available in class Test. Then how we can initialize them?
Right Way
class Info { private String Name=Mohit; private int age=25; Void displayInfo() { System.out.println(Name=+name); System.out.println(Age=+age); }} class Test { Public static void main(String args[]) { Info person1=new Info(); Info person2=new Info(); person1.displayInfo(); person2.displayInfo();
class Info { private String Name; private int age; Void displayInfo() { System.out.println(Name=+name); System.out.println(Age=+age); }} class Test { Public static void main(String args[]) { Info person=new Info(); person.name=Ram; // Wrong person.age=25; // Wrong person.displayInfo(); }}
}}
But now the problem is that we are creating 2 objects, person1 and person2. But both the objects are initialized with same data. One solution to the problem is Constructor. class Info { private String Name; private int age; Info() { name=Mohit; age=25; } Info(String s, int a) { name=s; age=a; }
Void displayInfo() { System.out.println(Name=+name); System.out.println(Age=+age); } } class Test { Public static void main(String args[]) { Info person1=new Info(); Info person2=new Info(Sumit,30);
person1.displayInfo(); person2.displayInfo();
}}