Home > Mobile >  why i can't able to access super class variable in sub class?
why i can't able to access super class variable in sub class?

Time:02-02

class customer {
    
    String Customer_Name;
    }

class login extends customer {
   public void temp(){
            System.out.println("Customer name is : = " Customer_Name);
        }
}

Here assume that object name is obj which is object from login class if i want to print Customer_Name so how can i print that.

i get answer as 0

suppose that i created one object and call temp function

login obj=new login();

obj.temp();

CodePudding user response:

The problem in this case I think is that it doesn't print the name but instead prints null, or at least that's what I understand. In that case you should do a method to set the name, remember to call before print the name, or you can as well pass the name in the constructor.

constructor of login:

login(String name){
        Customer_Name = name;
    }

a function like this inside login:

public void setCustomerName(String name){
        Customer_Name = name;
    }

this work pretty fine to me

CodePudding user response:

Format your code and also use Java naming convention:

You were trying to access a null variable customerName.

class Customer {
    String customerName = "Something";
}
class LogIn extends Customer {
   public void temp(){
            System.out.println("Customer name is : = "   customerName);
        }
}
LogIn logIn = new LogIn();
logIn.temp();

Output:

Customer name is : = Something

  •  Tags:  
  • Related