0

I have created a class building with constructor :

public class Building {
    private String Adress;
    private String Town;
    public Building(String A, String T) throws NullPointerException {
        if (A == null || T == null) {
            throw new NullPointerException();
        }
        else{
        Adress = A;
        Town = T; 
            System.out.println(Adress+Town);}
    public String getAdress() {
        return Adress
    }

    }

After that in main i do this :

 public static void main(String[] args) {
        try{Building MyBuilding = new Building("Prelungirea Ghencea", "Tulcea");}
             catch(NullPointerException e){
            System.out.println("Adresa sau Orasul lipsesc");
        }}

And when I want to call

`MyBuilding.getAdress()`

, copilator is saying that object MyBuilding does not exist. The statement from try/catch is not creating the object? I should create object Building after all try and catch blocks?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • You've got a problem with variable ***scope***. The MyBuilding object is visible only within the try block since that is where it was declared. Search on and read up on variable scope for the important details. – Hovercraft Full Of Eels Sep 04 '17 at 12:28
  • **MyBuilding** is only declared inside the **try-catch** scope in the main method... so you can only there call the getter!! – ΦXocę 웃 Пepeúpa ツ Sep 04 '17 at 12:28
  • As an aside, you will want to learn and use [Java naming conventions](http://en.wikipedia.org/wiki/Naming_convention_(programming)#Java). Variable names should all begin with a lower letter while class names with an upper case letter. Learning this and following this will allow us to better understand your code, and would allow you to better understand the code of others. – Hovercraft Full Of Eels Sep 04 '17 at 12:28
  • Aside #2: Don't do this: `throw new NullPointerException();`. Instead use a better and more informative exception class and message, perhaps throw an [IllegalArgumentException](http://docs.oracle.com/javase/8/docs/api/java/lang/IllegalArgumentException.html), and be sure to pass in an informative String into its constructor when you do. – Hovercraft Full Of Eels Sep 04 '17 at 12:34

0 Answers0