using two classes in java - java

I am trying to use two classes Member class and Website class to talk to each other. I want to use the code which is in the setloggedInStatus() method in the Member class and be able to use it in the memberLogin() method which is in the Website class. I used the Member memberObject = new setloggedInStatus(); code but its giving me an error.
I Would appreciate any help. Thanks in advance
Website class
public class Website
{
// declaration of vars
private String websiteName;
private int hits;
private double salesTotal;
/**
* Constructor for objects of class Website
*/
public Website(String websiteName)
{
// initialise instance variables
this.websiteName = websiteName;
}
Member memberObject = new setloggedInStatus();
public void memberLogin() {
}
}
Member class
public class Member
{
// varibales declaration
private String email;
private int membershipNumber;
private boolean loggedInStatus;
/**
* Constructor for objects of class Member
*/
public Member(String memberEmail, int newMembershipNumber )
{
// initialise instance variables
email = memberEmail;
membershipNumber = newMembershipNumber;
}
//loggedInStatus method
public void setloggedInStatus() {
if (email != null && membershipNumber != 0) {
loggedInStatus = true;
System.out.println("you are logged in ");
}
else {
loggedInStatus = false;
System.out.println("you are not logged in");
}
}
}

If you wanted to use the functionality of Member inside the class Website, you would need to import it via import Member at the top of the Website file (depending on if they're in the same folder/package). This will make it available inside the file.
You could then create a new Member object via Member member = new Member(params go here);
Then, you could call the methods contained inside your Member class from your created member object, for example member.setLoggedInStatus();
EDIT: Did this answer your question?

if the Website Class and the Member Class are in the same package you have to create an object of Member like this:
String email = "Example#examplemail.com";
int id = 3; //Example id
Member the_member = new Member(email,3);
If you want to call the public void setloggedInStatus() method you can simply do something like this with the previous object created:
the_member.setloggedInStatus();
If the two classes are not in the same package you have to import the class Member with
import Member

Related

Adding a new member variable to existing java POJO

Hi want to add new field boolean hasXYZ to an existing class which has two member variables. This class is widely used in the code and I want to add the new field in a way that I do not want to change all of the
new demoClass() calls to include the new field hasXYZ. And I was hasXYZ more like a on demand field .. so effectively, I guess two set of constructor .. one which works and other which takes additional boolean and sets hasXYZ. Thoughts on how I can do this ?
#Value
#NonFinal
public class demoClass implements demoInterface {
int integerMember;
long longMember;
}
Overload the constructor:
public class demoClass implements demoInterface {
int integerMember;
long longMember; // these should probably be private
boolean hasXYZ;
public demoClass( int integerMember, long longMember) {
this.integerMember = integerMember;
this.longMember = longMember;
}
public demoClass( int integerMember, long longMember, boolean hasXYZ) {
this.integerMember = integerMember;
this.longMember = longMember;
this.hasXYZ = hasXYZ;
}
}
Then you won't have to modify how you create the objects.

Cannot find Symbol error in Java - why?

I am having a hard time understanding the object oriented world. I am working on a homework assignment and I can't understand why I am getting an error here. The issue I am having is in the add method. I am using the Netbeans IDE (per professor requirement) and the problem I am getting is in the add method. There are two errors that both say "Cannot find Symbol"; one is in reference to the variable customers while the other is in reference to the variable numCustomer. I am trying to understand what I am doing wrong, not just how to fix it.
What I have so far:
package homework6;
/**
*
* #author christian
*/
public class Homework6 {
// Declare variables
private int numCustomers = 0;
private Customer customer;
// Constructor
public Homework6() {
Customer[] customers = new Customer[50];
}
/**
* #param args the command line arguments
*/
public void main(String[] args) {
System.out.println("Christian Beckman N00963294");
System.out.println("Homework 6");
System.out.println(); // Prints a blank line
// Create and instance of Homework6
Homework6 homework6 = new Homework6();
homework6.execute(args);
}
private void add(Customer customer) {
int i = 0;
customers[i] = customer;
i++;
numCustomer++;
}
private void displayCustomers() {
}
private void execute(String[] args) {
}
private int getTotal() {
}
private void readFile(String filename) {
}
}
Your variable is numCustomers with an 's' but your method refers to numCustomer++; without an 's'.
It should be:
numCustomers++;
For
private Customer customer;
it should probably be:
private Customer[] customers;
Be very careful in your code where you refer to customer and customers. It looks like you are using the convention "customer" for just one and "customers" for the array. If that is too subtle for you then consider changing to something like oneCustomer and allCustomers.
You create an array of Customer objects in the constructor, then the array is immediately destroyed. Try declaring it like this:
public class Homework6 {
// Declare variables
private int numCustomers = 0;
private int i = 0;
private Customer customer;
private Customer[] customers;
// Constructor
public Homework6() {
customers = new Customer[50];
}
...
The reason for this, is any variables declared inside a method (in this case, the constructor) has something called local scope which means it can ONLY be accessed inside that method. The variables you declare outside the methods have something called global scope, which means that variable can be accessed across all the methods in a class.
For the same reason as above, i will keep resetting to 0 each time you call the add function. To fix that, declare private int i = 0 above the constructor with the other variables. Then write the method like so:
private void add(Customer customer) {
customers[i] = customer;
i++;
numCustomers++;
}
Also, whenever you do numCustomer++ in the add method, you should put numCustomers++ like above because you declared numCustomers with an 's' at the end. Has to match EXACTLY.

Calling an inner class in a main method in java

So I've already tried looking up what's causing this and comparing my code for any possible errors to others and I have yet to find anything else that would lead to this issue.
I'm trying to call the inner class Pair in order to store data.
Quick info about my project.
Take voting data and determine someone's political stance on it.
Right now I'm just trying to parse the data.
Example data
Rep1[tab]D[tab]-+-+-++---
I'm storing it as...
ArrayList<Pair<String,String>>
So rep1 is the place in the ArrayList and then D and -+-+-++--- are the pair.
But I'm having an issue with trying to instantiate the Pair class " non-static variable this cannot be referenced from a static context"
specifically
C:\Users\Stephanie\Desktop>javac DecisionTree.java
DecisionTree.java:26: error: non-static variable this cannot be referenced from a static context
Pair pair = new Pair();
^
1 error
Code:
public class DecisionTree{
public static void main(String[] args)
{
ArrayList<Pair> data = new ArrayList<Pair>();
FileReader input = new FileReader ("voting-data.tsv");
BufferedReader buff = new BufferedReader(input);
String line = null;
while((line=buff.readLine())!=null)
{
Pair pair = new Pair();
String[] array = line.split("\\t");
pair.setLabel(array[1]);
pair.setRecord(array[2]);
data.add(pair);
}
}
/**
* Private class to handle my inner data
*/
public class Pair
{
private String label;
private String record;
/**
* contructor
*#param String label, the label of the person's party
*#param String record, their voting record
*/
private Pair(String label, String record)
{
this.label = label;
this.record = record;
}
/**
* empty contructor
*/
private Pair()
{
}
/**
* get the label
*#return String label, the label of the person's party
*/
private String getLabel()
{
return label;
}
/**
* get the record
*#return String record, their voting record
*/
private String getRecord()
{
return record;
}
/**
* set the label
*#param String label, the label of the person's party
*/
private void setLabel(String label)
{
this.label=label;
}
/**
* set the record
*#param String record, their voting record
*/
private void setRecord(String record)
{
this.record=record;
}
}
}
Thanks! I feel like I'm missing something really basic, it's just been a long time since I've used Java
Non-static inner classes are associated with an instance of the enclosing class in Java. This means that an instance of class Pair in your example belongs to a specific instance of DecisionTree. You can only create it in the context of an instance of DecisionTree. You can't directly create a Pair using new Pair() in the main() method, because that method is static (so, it's not associated with an instance of DecisionTree).
If you don't want this, make the inner class static:
public class DecisionTree {
// ...
public static class Pair {
// ...
}
}
Make your Pair static, i.e.:
public static class Pair
Otherwise you cannot construct a Pair object in main(), because it is a static method. Inner classes (as opposed to static nested classes) require a surrounding instance.
Also your comment says Pair is private, but the class is marked public. Make it private if that is your intent.
Pair is an inner class. Instances of an inner class are associated with instances of the class they are a member of, and can only be created in the context of a parent instance.
If you declare Pair static it will become a nested class, which is more like a regular class. The enclosing class only contributes its name.

Using object reference to get methods from another class

So I have a concrete class and an abstract class and I am trying to access methods from the concrete class from the abstract one. Store currently contains many getters that the member class needs. Currently get null pointer exception.
public abstract class members{
// Trying to refrence the store object
Store store;
public void someMethod(){
// I want to be able to access all the methods from the store class
// eg
store.showVideoCollection();
}
}
public class store {
// This class has already been instantiated, just one object for it.
public void showVideoCollection(){
// Stuff here
}
public void otherMethod(){
// Stuff here
}
}
EDIT:
In the main method
public class start {
public start() {
store = new Store(); // Don't want to create more than 1 store object.
}
Thanks
In order to store a Store instance you must instantiate it. As is, you declare the variable store but you never initialize it (so it's null). I think you wanted something like
// Trying to refrence the store object
Store store = new Store(); // <-- create a Store and assign it to store.
Alternatively, you could make Store a Singleton. The linked Wikipedia page says (in part) the singleton pattern is a design pattern that restricts the instantiation of a class to one object.
public final class Store {
public static Store getInstance() {
return _instance;
}
private static final Store _instance = new Store();
private Store() {
}
public void showVideoCollection(){
// Stuff here
}
public void otherMethod(){
// Stuff here
}
}

Get a variable from a different class

So I'm trying to cut back on some of the code that's been written. I created a separate class to try this. I have that class working correctly, however the old one uses variables that are now in the separate class. How do I access these variables? Unfortunately I can't share all the code for this, but I can give out small pieces that I think are necessary. Thanks for the help
This is from the old class that I am now trying to bring the variable to: I'm trying to bring "loader" over
// XComponentLoader loader = null;
fixture.execute(new OpenOfficeOpener());
component = loader.loadComponentFromURL("file:///"+System.getenv("BONDER_ROOT") + "/ControlledFiles/CommonFiles/"+spreadsheet, "_blank", 0, loadProps);
You can write getters for the members that you need to be visible outside. Example:
public class MyClass {
private int member1;
private String member2;
public int getMember1() {
return member1;
}
public String getMember2() {
return member2;
}
}
Now both member1 and member2 can be accessed from the outside.
There are a couple of solutions to your problem. What I would suggest is to add a method in your class to return the value to the new program, or pass it as a parameter.
An example of this on a higher level might look like this:
x = newClass.getValX()
It sounds like you're looking for a static field, though if is the case you almost certainly reconsider your current design.
public class YourClass {
private static XComponentLoader loader;
public YourClass() {
YourClass.loader = new XComponentLoader();
}
}
And to access it from another class:
public YourOtherClass {
public void yourMethod() {
YourClass.loader ...
}
}
If loader is static, than do something like:
component = TheOtherClass.loader.loadComponentFromURL( ...
Otherwise, your new class needs a reference to an instance of the other class. You could pass it with the constructor:
public class NewClass {
private OldClass oldClass = null;
public NewClass(OldClass oldClass) {
this.oldClass = oldClass;
}
// ...
fixture.execute(new OpenOfficeOpener());
// assuming, loader is a public field on OldClass.
// a getter (getLoader()) is preferred
component = oldClass.loader.loadComponentFromURL("file:///"+System.getenv("BONDER_ROOT") + "/ControlledFiles/CommonFiles/"+spreadsheet, "_blank", 0, loadProps);
// ...
}
I've you've split functionality into two classes, then you may want to have one class instantiate another.
If you've put your new code in Class B then it might look like this.
public class A {
// Class B instance
B b = new B();
public void doSomething() {
b.loadComponentFromURL("someurl");
}
}
Or if the loader is an instance itself, you could call it like this.
b.getLoader().loadComponentFromURL("someurl");

Categories

Resources