How to access data members from another class..
I am trying to access private data members from one class in another class..
eg: Trying to use a print() method in one class and trying to access the data members with getID()..
However this throws and error "Non static method cannot be referenced from static context.."
What have I done wrong and how could I correct it? Code snippets below..
Part of my print()
public void inorderPrint()
{
if (left != null)
left.inorderPrint( );
System.out.print(CD.getID()+"\t");
if (right != null)
right.inorderPrint( ); }
Part of my CD class
public class CD {
private int ID;
private String artist;
private String title;
private String company;
/** Creates a new instance of CD */
public CD(int id, String ar, String ti, String co)
{
ID = id;
artist = ar;
title = ti;
company = co;
}
public int getID()
{ return ID; }
public String getArtist()
{ return artist; }
public String getTitle()
{ return title; }
public String getCompany()
{ return company; }
}
Thankyou for your time..
[1436 byte] By [
Code_Nerd] at [2007-11-11 7:05:51]

# 1 Re: How to access data members from another class..
I see one suspicious line in the inorderPrint()
System.out.print(CD.getID()+"\t");
you cannot use the CD class' getID method like it was a static method,
and if you think of it, what id should that method return ? :cool:
sjalle at 2007-11-11 22:39:19 >

# 2 Re: How to access data members from another class..
Thankyou for your reply.. :)
That is what I am having problems with, how to access the members of the CD class in my BTNode class?
# 3 Re: How to access data members from another class..
If you have two classes ClassA and ClassB and you want ClassB to invoke
non-static methods in ClassA then ClassB must have access to an instance of
ClassA. You can do this many ways but two of them are:
1: ClassB has a constructor that takes an instance of ClassA
2: ClassB has a method, e.g. setClassA(ClassA aClass), that supplies it
with an instance of ClassA.
So, using method 1:
ClassA aClass=new ClassA();
ClassB bClass=new ClassB(aClass);
A part of ClassB:
private ClassA aClass=null;
private int id=-1;
// constructor
public ClassB(ClassA aClass) {
this.aClass=aClass;
}
public void someBMethod() {
this.id=aClass.getID(); // invoke a ClassA method
}
sjalle at 2007-11-11 22:41:23 >
