Language Families

Hi I was working on the freeform project in java, and I dont get why cant I access the constructors variables as they are in the same class from the code below:

public class Language{
  protected String name;
  protected int numSpeakers;
  protected String regionsSpoken;
  protected String wordOrder;
  
  Language(String langName, int speakers, String regions, String wdOrder){
    this.name = langName;
    this.numSpeakers = speakers;
    this.regionsSpoken = regions;
    this.wordOrder = wdOrder;
  }
  
  public void getInfo(){
     System.out.println(langName + " is spoken by " + speakers + " people mainly in " + regions + ".");
    System.out.println("The language follows the word order: " + wdOrder);
  }
  
  
  public static void main(String[] args){
    Language Spanish = new Language("Spanish", 100000000, "Spain and Mexico", "subject-verb-object" );
    Spanish.getInfo();
  }
}

I get the erros saying the variables from my method getInfo() cant be found. The code below using this and the variables from the class works.

public class Language{
  protected String name;
  protected int numSpeakers;
  protected String regionsSpoken;
  protected String wordOrder;
  
  Language(String langName, int speakers, String regions, String wdOrder){
    this.name = langName;
    this.numSpeakers = speakers;
    this.regionsSpoken = regions;
    this.wordOrder = wdOrder;
  }
  
  public void getInfo(){
     System.out.println(this.name + " is spoken by " + this.numSpeakers + " people mainly in " + this.regionsSpoken + ".");
    System.out.println("The language follows the word order: " + this.wordOrder);
  }
  
 public static void main(String[] args){
    Language Spanish = new Language("Spanish", 100000000, "Spain and Mexico", "subject-verb-object" );
    Spanish.getInfo();
  }
}

Could someone explain as I might miss a point here. Thanks

You understand the scope rules of Java? langName only exists within the constructor method. Parameters are only accessible in the method they are the parameter of.

that is why we use class attributes like this.name, which we can access in all methods of the class (private), then there are also protected (also child classes) and public

1 Like