+ 2
Constructors are not used to "access" private objects. Constructors are used to initialize class members, regardless of their access specification. In your code, you are trying to print m.band, which is private. It has nothing to do with the constructor.
5th Jan 2019, 2:14 PM
Hatsy Rei
Hatsy Rei - avatar
+ 1
private members are accessible only within the same class where they are declared. You are declaring the variable band within the class metal but you are accessing the variable band within class heavy //you can do as follows class metal { private String band; metal(String b) { band = b; } public String getVal() { return band; } } public class heavy{ public static void main(String[ ] args) { metal m = new metal("Metallica"); String r = m.getVal(); System.out.println(r); } }
5th Jan 2019, 2:15 PM
Rishi Anand
Rishi Anand - avatar
+ 1
You will refer this solution also.... By the way, private members can be accesible only in existing class. https://code.sololearn.com/ckd3VGvbjTsO/?ref=app
5th Jan 2019, 2:52 PM
Bipin Tatkare
Bipin Tatkare - avatar