Click here to Skip to main content
14,699,232 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi i try coded
This my source

public class Data {
private String name;
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return this.name;
}
}


public class Setinfo{
public void Showmessage()
{
Scanner sc = new Scanner(System.in);
Data d= new Data();
System.out.print("name : ");
d.setName(sc.next());
}
}


public class Info extends Setinfo{
public void Result()
{
Data d = new Data();
Showmessage();
System.out.print("name : "+d.getName());
}
}



public class Homework {
public static void main(String[] args) {
Info x = new Info();
x.Result();
}

}


I get name = null ? idk how to use encapsulation vs inheritance but i know how to use encapsulater
Posted
Comments
Maarten Kools 2-Sep-13 4:25am
   
You're both allocating a new Data instance in Showmessage and Result. So obviously, after allocating a new instance, name will be null again. So store your Data instance in a member variable and use that instead.
KururuLABO 2-Sep-13 4:41am
   
pls show you example ? i don't understand
Maarten Kools 2-Sep-13 4:49am
   
Showmessage and Result are two separate methods. By allocating a new Data instance in both those methods, they'll use a unique instance. So the instance used in Showmessage isn't the same as in Result.

To fix that, make sure you keep a member variable of Data in your SetInfo class. e.g.

class SetInfo
{
protected Data _d = new Data();

public void Showmessage() { _d.SetName("..."); }
}

class Homework : SetInfo
{
public void Result() { string s = _d.getName(); }
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900