+ 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.
+ 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);
}
}
+ 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