please help me with self-reference pointer - java

i have written two classes first one Member and second one Store. and i wrote a method which can create an object from the member class and i am trying to to write a field store of type Store in the Member class and i want it store a reference to the store the member has entered.
some told me to do this :
memberRegister() needs to be passed, as an argument, a pointer to the Store object that you are currently in.
In fact, the Store object needs to be able to tell the Member object "point to me". That is, the Store object needs a pointer to itself.
but i did not get it
this is Member class
private int pinNumber;
private String name, id;
private Store store;
/**
* Constructor for objects of class Member
*/
public Member(String name, String id, int pinNumber, Store store)
{
// initialise instance variables
this.name = name;
this.id = id;
this.pinNumber = pinNumber;
checkId();
checkPinNumber();
}
/**
* An example of a method - replace this comment with your own
*
* #param y a sample parameter for a method
* #return the sum of x and y
*/
private void checkId()
{
// put your code here
int length;
length = id.length();
if (length > 10 ){
System.out.println("lentgh must be at 10 ");
}
}
private void checkPinNumber()
{
int length;
length = id.length();
if ((length > 4) && (length < 4 )){
System.out.println("lentgh must be at 4");
}
class store
private String storeName;
private int total;
private Member member;
/**
* Constructor for objects of class Store
*/
public Store(String storeName, int total)
{
// initialise instance variables
this.storeName = storeName;
this.total = total;
}
/**
*
*/
public String getStoreName()
{
return storeName;
}
/**
* An example of a method - replace this comment with your own
*
* #param y a sample parameter for a method
* #return the sum of x and y
*/
public Member memberRegister(String name, String id, int pinNumber)
{
// put your code here
Member member;
member = new Member(name, id, pinNumber)
return member;
}

your memberRegister method doesn't invoke your Member constructor correctly:
public Member memberRegister(String name, String id, int pinNumber)
{
// put your code here
Member member;
member = new Member(name, id, pinNumber, this) //this passes in a reference to your store
return member;
}
Then you assign the reference in your Member constructor:
public Member(String name, String id, int pinNumber, Store store)
{
// initialise instance variables
this.name = name;
this.id = id;
this.store = store //where this.store is a Store
this.pinNumber = pinNumber;
checkId();
checkPinNumber();
}
Hope that helps. By the way, update the comments in a way, that they match your code.

Using the keyword this is how you are able to get a self-referential pointer. You should be able to do as #Kerrek SB suggested and return new Member(name, id, pinNumber, this) from inside the memberRegister method.

See in your case passing this keyword to method memberRegister is useless
returning this keyword is useful.
to know more about this keyword check this

Related

Initializing objects with static values

Every time I create an object of the class it returns the same value every time, even if the object is different with different values. How can I make sure that this doesn't happen?
class Something{
protected String name;
protected static double price; // need the value later
public Something(String xName, double xPrice){
name = xName;
price = xPrice;
}
public String returnName(){
return name;
}
public static returnPrice(){
return price;
}
}
If you need the value of price as unique to object, you should not declare it as static. If you declare as static, it will be accessible within all objects of given class and it won't belong to object.

String changes to null

Good morning, I'm using the following constructor code and for some reason the "position" variable sets to null every time a new object is created.
This is my class code
public class Employee
{
private String name;
private int idNumber;
private String department;
private String position;
public Employee(String nam, String depart, String posi, int id)
{
name = nam;
department = depart;
posi = position;
idNumber = id;
}
}
And this is the line I'm using to create the object.
Employee sMeyers = new Employee("Susan Meyers", "Accounting", "Vice President", 47899);
It should be
position = posi;
and not
posi = position;
You're assigning here a null variable (position) to an immutable parameter (posi).
The other answers already stated that your mistake is
posi = position
Luiggi Mendoza also made a comment stating that you should use "this"!
I just want to give you a complete example on how it should be done.
public class Employee
{
private String name;
private int idNumber;
private String department;
private String position;
public Employee(String name, String department, String position, int idNumber)
{
this.name = name;
this.department = department;
this.position = position;
this.idNumber = idNumber;
}
}
Accessing your class variables explicit by this also spares you the hassle of making up new variable names like "nam" and "pos".
For your constructor argument posi, you want to take that value and assign it to one of the class fields which in this example would be position. Now, what you're doing is assigning position (which is null) to posi. So you're overwriting your argument with null and not really doing anything with it.
What you want to do is the following:
position = posi;
which assigns the constructor argument i.e. "Vice President to the class field position.
Remember the variable on the right is assigned to the variable on the left.
Thats because you of this statement:
posi = position;
Change it to
position =posi;
Use "this" pointer to avoid these errors. Happy Coding !!

Array of custom Java objects

I am trying to create an array of Person (a class that with variables String name, and double total). But for some reason, creating a second Person replaces(?) the first person. . .
Person[] p = new Person[40];
p[0] = new Person("Jango", 32);
p[1] = new Person("Grace", 455);
System.out.println( p[0].getName() );
System.out.println( p[1].getName() );
System.out.println( p[0].equals(p[1]) );
The output is:
Grace
Grace
false
Why isn't it:
Jango
Grace
false
????????????
public class Person {
#SuppressWarnings("unused")
private Person next;
private String name;
private double total;
public Person(String _name)
{
name = _name;
total = 0.0;
next = null;
}
public Person(String _name, double _total)
{
name = _name;
total = _total;
next = null;
}
public String getName()
{
return name;
}
}
Your problem is that the name instance variable is declared as static, making it a class variable. Any change to name will be changed for every instance of that class.. You need to remove the static identifier from name and from total and your code will work fine.
Currently these variables are static which means that they they will retain the last values assigned.
private static String name;
private static double total;
You need to make these fields class instance variables:
private String name;
private double total;
See Understanding Instance and Class Members
Your fields are static. They should not be, if you want them to be able to store a separate instance of a name and total for each instance of the class.

arrays and listview for android (java)

I am trying to show just the name of the player from the array into the list view. this is my code for that:
player_List.setAdapter(new ArrayAdapter<Player>(this, android.R.layout.simple_list_item_1, dataStore.getPlayers()));
im getting all the information from that array using this call. i am unsure how to just call the name.
this is the coding for my data store:
/**
* This class is essentially a global library for the Scoresheet.
* It provides methods through which the Players and Teams can be accessed
* from any part of the application.
* The saving/loading of application data will also be handled through this
* class.
*
* You can access this DataStore by calling:
* DataStore dataStore = ((DataStore)getApplicationContext());
* From any Activity
*/
public class DataStore extends Application {
// Create ArrayLists to hold all our Player and Team objects
private ArrayList<Player> players = new ArrayList<Player>();
private ArrayList<Team> teams = new ArrayList<Team>();
// File names for our internal storage:
private String playerFileName = "players";
private String teamFileName = "teams";
/**
* Add a Player object to the list of players.
* #param p The Player object to add
*/
public void addPlayer(Player p){
this.players.add(p);
}
/**
* Merge an ArrayList of Player objects with the current collection of Players
* #param players ArrayList of Player objects to add to the collection
*/
public void addPlayers(ArrayList<Player> players){
Iterator<Player> it = players.iterator();
while (it.hasNext()){
this.players.add(it.next());
}
}
/**
* Return an ArrayList of player objects containing all Players
* #return
*/
public ArrayList<Player> getPlayers(){
return this.players;
}
and this is my player class:
public class Player implements Serializable{
// Randomly generate serial ID
private static final long serialVersionUID = 7423594865734681292L;
private static int ID = 0; // Class variable
public String name;
private int id;
public Player(String name) throws Exception{
this.setId(ID);
ID++; // Increment class ID counter
if (!this.setName(name))
throw new Exception("Invalid Name"); // This is the only way to prevent the object being instantiated if it has an invalid name
}
public String getName() {
return name;
}
/**
* Set the players name as desired.
* #param name
* #return true on success, false on fail
*/
public boolean setName(String name) {
// Only update the name if we are actually given a string
boolean success = false;
name = name.trim();
if (!name.equals("")){
this.name = name;
success = true;
}
return success;
}
public int getId() {
return id;
}
private void setId(int id) {
this.id = id;
}
}
Use CustomAdapter and set in getView(...) method
Like,
Player player = getPlayers().get(position);
textview.setText(player.name)
see this example,,
http://www.softwarepassion.com/android-series-custom-listview-items-and-adapters/
http://jnastase.alner.net/archive/2010/12/19/custom-android-listadapter.aspx
I'm no expert on android listview, but if it just uses toString to decide what to show, implement toString to just return name:
public String toString() { return name; }

Use of "this" keyword in java [duplicate]

This question already has answers here:
What is the meaning of "this" in Java?
(22 answers)
Closed 7 years ago.
I was studying method overriding in Java when ai came across the this keyword. After searching much about this on the Internet and other sources, I concluded that thethis keyword is used when the name of an instance variables is same to the constructor function
parameters. Am I right or wrong?
this is an alias or a name for the current instance inside the instance. It is useful for disambiguating instance variables from locals (including parameters), but it can be used by itself to simply refer to member variables and methods, invoke other constructor overloads, or simply to refer to the instance. Some examples of applicable uses (not exhaustive):
class Foo
{
private int bar;
public Foo() {
this(42); // invoke parameterized constructor
}
public Foo(int bar) {
this.bar = bar; // disambiguate
}
public void frob() {
this.baz(); // used "just because"
}
private void baz() {
System.out.println("whatever");
}
}
this keyword can be used for (It cannot be used with static methods):
To get reference of an object through which that method is called within it(instance method).
To avoid field shadowed by a method or constructor parameter.
To invoke constructor of same class.
In case of method overridden, this is used to invoke method of current class.
To make reference to an inner class. e.g ClassName.this
To create an object of inner class e.g enclosingObjectReference.new EnclosedClass
You are right, but this is only a usage scenario, not a definition. The this keyword refers to the "current object". It is mostly used so that an object can pass itself as a parameter to a method of another object.
So, for example, if there is an object called Person, and an object called PersonSaver, and you invoke Person.SaveYourself(), then Person might just do the following: PersonSaver.Save( this );
Now, it just so happens that this can also be used to disambiguate between instance data and parameters to the constructor or to methods, if they happen to be identical.
this keyword have following uses
1.used to refer current class instance variable
class Student{
int id;
String name;
student(int id,String name){
this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
s1.display();
s2.display();
}
}
here parameter and instance variable are same that is why we are using this
2.used to invoke current class constructor
class Student{
int id;
String name;
Student (){System.out.println("default constructor is invoked");}
Student(int id,String name){
this ();//it is used to invoked current class constructor.
this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student e1 = new Student(111,"karan");
Student e2 = new Student(222,"Aryan");
e1.display();
e2.display();
}
}
3.this keyword can be used to invoke current class method (implicitly)
4.this can be passed argument in the method call
5.this can be passed argument in the constructor call
6.this can also be used to return the current class instance
This refers current object. If you have class with variables int A and a method xyz part of the class has int A, just to differentiate which 'A' you are referring, you will use this.A. This is one example case only.
public class Test
{
int a;
public void testMethod(int a)
{
this.a = a;
//Here this.a is variable 'a' of this instance. parameter 'a' is parameter.
}
}
Generally the usage of 'this' is reserved for instance variables and methods, not class methods ...
"class methods cannot use the this keyword as there is no instance for
this to refer to..."
http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
Here's a trivial example ...
public class Person {
private String name;
private int age;
private double weight;
private String height;
private String gender;
private String race;
public void setName( String name ) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setAge( int age) {
this.age = age;
}
public int getAge(){
return this.age;
}
public void setWeight( double weight) {
this.weight = weight;
}
public double getWeight() {
return this.weight;
}
public void setHeight( String height ) {
this.height = height;
}
public String getHeight() {
return this.height;
}
public void setGender( String gender) {
this.gender = gender;
}
public String getGender() {
return this.gender;
}
public void setRace( String race) {
this.race = race;
}
public String getRace() {
return this.race;
}
public void displayPerson() {
System.out.println( "This persons name is :" + this.getName() );
System.out.println( "This persons age is :" + this.getAge() );
System.out.println( "This persons weight is :" + this.getWeight() );
System.out.println( "This persons height is :" + this.getHeight() );
System.out.println( "This persons Gender is :" + this.getGender() );
System.out.println( "This persons race is :" + this.getRace() );
}
}
And for an instance of a person ....
public class PersonTest {
public static void main( String... args ) {
Person me = new Person();
me.setName( "My Name" );
me.setAge( 42 );
me.setWeight( 185.00 );
me.setHeight( "6'0" );
me.setGender( "Male" );
me.setRace( "Caucasian" );
me.displayPerson();
}
}
In case of member variable and local variable name conflict, this key word can be used to refer member variable like,
public Loan(String type, double interest){
this.type = type;
this.interest = interest;
}
if you have knowladge about c,c++ or pointers, in that language this is a pointer that points object itself. In java everything is reference. So it is reference to itself in java. One of the needs of this keyword is that:
Think that this is your class
public class MyClass
{
public int myVar;
public int myMethod(int myVar)
{
this.myVar = myVar; // fields is set by parameter
}
}
If there is not this keyword you it is confused that this is paramter or class field.When you use this.myVar it refers field of this object.
I would like to modify your language. The this keyword is used when you need to use class global variable in the constructors.
public class demo{
String name;
public void setName(String name){
this.name = name; //This should be first statement of method.
}
}
this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
One more thing that should be in mind is that this keyword might be the first statement of your method.
This is used in java. We can use in inheritance & also use in method overloading & method overriding. Because the actual parameter or instance variable name has same name then we can used this keyword complsary . But some times this is not same as when we can not use this keyword complsary.....
Eg:- class super
{
int x;
super(int x)
{
this.x=x
}
}

Categories