Access variables from other classes - java

I have a class that is receiving input from users. Then the results are parsed and stored in this class I placed below. Then there is a separate class that is taking what is stored in the class below and creating something with it. I would post all of the classes, but there are just too many lines of code. I have placed below the exact class I have a question on (minus other variables of the same type for simplicity)
I would like to know if there is a way to access variables from an abstract class within another class. Here is my abstract class:
public abstract class ParsResults {
public String AnsName;
public String AnsType;
}
Then I have another class that needs these variables. Im just not sure how to approach it. Thanks in advance.

There is absolutely no way accessing instance variables of instances of abstract classes, since they can not have instances.
Please do not make instance variables public, make them private and provide getters and setters.
Your instance variables should start with a lowercase letter.
If you have an instance of a concrete subclass of ParsResults, you can access its values using the getters (see point 2.).

To share variables between classes, there are three ways:
public class Human {
// instance variables
public String name;
public int age;
//constructor, creates an instance of the Human class.
public Human(String s, int i){
name = s;
age = i;
}
}
in this case, your instance variables are public.
so in another class, when you create a instance of a Human class by calling:
Human aHuman = new Human(tom, 25);
then you can access the two instance variables directly. you can get its value by using:
String theHumanName = aHuman.name;
and you can set its value(change it) by using:
aHuman.name = "mike";
the two above lines will only work if your variables are public.
the reason you should make them private is to keep the values from being changed from outside the class. So if they are private then you create get and set methods, depending on the need.
Here is how it should be done:
public class Human {
// instance variables
private String name;
private int age;
//constructor, creates an instance of the Human class.
public Human(String s, int i){
setName(s);
setAge(i);
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the age
*/
public int getAge() {
return age;
}
/**
* #param age the age to set
*/
public void setAge(int age) {
this.age = age;
}
}
now from outside the class, you can call:
String theHumanName = aHuman.getName(); // this a method call, therefore you must have the parentheses
and you can set its value(change it) by using:
aHuman.setName("mike");

You have to instatiate that class, but you can't instantiate an abstract class.
So first create a not abstract class witch extends ParsResults, then instantiate this new class and in your main you can see the variables like this:
public class NewClass extends ParsResults {
//...
}
public static void main(String [] args){
NewClass nc = new NewClass();
// ...
System.out.println(nc.Name);
}

Related

How to change and get objects from aother class without declaring it?

I am new to java. I try to get and change objects from a class ( ex: Class Camera or Class Microphone and objects camera1, camera2, camera3 , microphone1, microphone2, microphone3 in their classes each with price, name, score ) i want to get the name of one object and change one's price from another class without making a new one.
This is the first class:
public class Microphone{
String name;
int price;
/** Constructors, setters and getters */
Microphone mic1 = new Microphone("mic1",200);
Microphone mic2 = new Microphone("mic2",300);}
This is the second class:
public class Camera{
String name;
int price;
/** Constructors, setters and getters */
Camera cam1 = new Camera("cam1",500);
Camera cam2 = new Camera("cam2",1000);}
In the main class ( or in a different class like Shop, menu etc ) i want to get the price of one's object, like cam1.getPrice and mic2.setPrice so i can compare to the stats of the player in the game if he can afford it and to change the price of it.
You can create an ArrayList in your Main class with your object type and manage them this way. You can then modify your objects as much as you'd like. If you create an interface class you can do something like this:
First create the interface class, I named mine Device and gave it one method, to set the cost. You can add whatever methods you need to add, like setDate, setModel, setName.... etc
public interface Device
{
void setCost(double costIn);
}
Next create the microphone class and have it implement Device. After, you will need to add the Device methods to the class.
public class Microphone implements Device
{
double cost = 0.0;
public void setCost(double costIn)
{
cost = costIn;
}
}
Here is another class example with Camera, also with one data member.
public class Camera implements Device
{
double cost = 0.0;
public void setCost(double costIn)
{
cost = costIn;
}
}
Now in your main class, you can have all of your Devices into one ArrayList for easy manipulation and control.
public static void main(String[] args) throws FileNotFoundException
{
ArrayList<Device> arr = new ArrayList<Device>();
arr.add(new Microphone());
arr.add(new Camera());
}
Honestly there is a lot of ways to go about what you are asking, this is just one example.
Create a class(It is also known as model class) such as Car.
Then define relevent attributes inside that class.
Put the full args constructor.
Make setters & getters.
public class Car {
private String name;
Car(String name){
this name=name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
So you can change or get on created object using getters & setters.
example : Car c1= new Car("Audi"); If you want to change name of Car
c1.setName("Toyota");

Java Inheritance: Calling a subclass method in a superclass

I'm very new to java and would like to know whether calling a subclass method in a superclass is possible. And if doing inheritance, where is the proper place to set public static void main.
Superclass
public class User {
private String name;
private int age;
public User() {
//Constructor
}
//Overloaded constructor
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return this.name;
}
public static void main(String []args) {
User user1 = new Admin("Bill", 18, 2);
System.out.println("Hello "+user1.getName());
user1.getLevel();
}
}
Subclass
public class Admin extends User {
private int permissionLevel;
public Admin() {
//Constructor
}
//Overloading constructor
public Admin(String name, int age, int permissionLevel) {
super(name, age);
this.permissionLevel = permissionLevel;
}
public void getLevel() {
System.out.println("Hello "+permissionLevel);
}
}
Short answer: No.
Medium answer: Yes, but you have to declare the method in the superclass. Then override it in the subclass. The method body from the subclass will be in invoked when the superclass calls it. In your example, you could just put an empty getLevel method on User.
You could also consider declaring User as an abstract class and declaring the getLevel method as abstract on the User class. That means you don't put any method body in getLevel of the User class but every subclass would have to include one. Meanwhile, User can reference getLevel and use the implementation of its subclass. I think that's the behavior you're going for here.
I'm very new to java and would like to know whether calling a subclass
method in a superclass is possible.
A superclass doesn't know anything about their subclasses, therefore, you cannot call a subclass instance method in a super class.
where is the proper place to set public static void main.
I wouldn't recommend putting the main method in the Admin class nor the User class for many factors. Rather create a separate class to encapsulate the main method.
Example:
public class Main{
public static void main(String []args) {
User user1 = new Admin("Bill", 18, 2);
System.out.println("Hello "+user1.getName());
user1.getLevel();
}
}
No, it is not possible to call sub class method inside super class.
Though it is possible to call different implementations of the same method in a client code while you have a variable with a super class type and instantiate it with either super class or sub class objects. It is called polymorphism.
Please, consider the following example:
public class User {
private String name;
private int age;
protected int permissionLevel;
public User() {
//Constructor
}
//Overloaded constructor
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return this.name;
}
public void getLevel() {
System.out.println("Hello "+ permissionLevel);
}
}
public class Admin extends User {
public Admin() {
//Constructor
}
//Overloading constructor
public Admin(String name, int age, int permissionLevel) {
super(name, age);
this.permissionLevel = permissionLevel;
}
#Override
public void getLevel() {
System.out.println("Hello "+permissionLevel);
}
public static void main(String []args) {
User user1 = new Admin("Bill", 18, 2);
System.out.println("Hello "+user1.getName());
user1.getLevel(); //call to subclass method
user1 = new User("John", 22); //the variable is the same but we assign different object to it
user1.getLevel(); //call to superclass method
}
}
Answering your second question, no, it does not matter where you place your main method as long as it is of right method signature. As you can see in my example I moved the method to Admin.java - it is still acceptable.
Calling subclass method in a superclass is possible but calling a subclass method on a superclass variable/instance is not possible.
In java all static variable and methods are considered to be outside the class i.e they do have access to any instance variable or methods. In your example above it will be wise to create a new class called Main and put public static void main in there but this is just a hygiene issue and what you have above will work except for the line.
user1.getLevel()
Use case: If employee eats, then automatically should sleep:-)
Declare two methods eat and sleep from class person.
Invoke the sleep method from eat.
Extend person in the employee class and override only the sleep method:
Person emp=new Employee();
emp.eat();
Explanation: As eat method is not in subclass, it will invoke the super class eat. From there, sub class's sleep will be invoked.

How to access a variable which is declared in a method belonging to another Java class?

I have recently started trying my hands at Java and I am stuck at this problem. I have two Java files called Main_file.java and Helper.java. The Helper.java file contains a String variable called the name, which I wish to access form my Mainfile.java and assign to a string variable x. The files look soemthing like this.
Main.java
public class Mainfile{
Helper myhelper =new MyHelper();
public void create_func(){
String x = /* assign the value name from the helper file */;
}
Helper.java
public class Helper{
public void add_name() {
String name = "New_name";
}
}
But this does not seem to work. I am not really sure if the method I am trying is right or wrong. Could somebody please help me? Thank you in advance.
The variable name you create in your Helper class is not class-member but only a member which exists in the method add_name()
If you want a class member you'll have to create it like this:
public class Helper{
String name = "New_name";
}
then you can access it like this:
public class MainFile{
Helper myHelper = new Helper();
public void create_func(){
String x = myHelper.name;
}
}
Many people will say that class-members "have" to be private, so it might be nicer to create getters and setters for the class member:
public class Helper{
private String name = "New_name";
public String getName() {
return name;
}
public void setName(String newName) {
name = newName;
}
}
public class MainFile{
Helper myHelper = new Helper();
public void create_func(){
String x = myHelper.getName();
}
}
You can not directly access a local variable of a method of another class. You can do it by making the method returning the object and access it by calling the method by an object of the class. This is how you can:
public class Mainfile{
Helper myhelper =new Helper();
public void create_func(){
String x = myhelper.add_name();
}
}
public class Helper{
public String add_name(){
String name = "New_name";
return name;
}
}

How do I make variables in a Main accessible to other classes?

For example I have a MovieDatabase class that contains a list of Movie objects. In my main code, I initialize all the objects in the MovieDatabase. However I wish to call this MovieDatabase in another class to access the library. How would I do this?
Do I add in get methods in my main code and return it? Or is there another way (eg. changing the list of objects to protected/public?)
Thanks!
Code's supposed to be 3 seperate classes, Main, MovieDatabase & Movie.
An instance of movieDatabase is initialized in Main. Upon construction, it calls loadMovieList() and populates the list from a text file. However I wish to call the same instantiation of movieDatabase from another class in order to access the movies, so that I do not have to repeat the loading.
public class Main {
public static void main(String[] args) {
MovieDatabase movieDatabase = new MovieDatabase();
}
public class MovieDatabase {
ArrayList<Movie>movieList = new ArrayList<Movie>();
String fileAddress = "D:/Users/Mine/School/Java/CZ2002_Assignment/src/MovieDatabase/movieDatabase.txt";
public MovieDatabase()
{
numOfMovie=0;
loadMovieList();
}
public int getNumOfMovie() {
return numOfMovie;
}
public void addMovieToList(Movie movie) {
movieList.add(movie);
numOfMovie++;
}
public Movie selMovieByID(int movieID) {
int index=-1;
for (Movie m : movieList) {
index++;
if (m.getMovieID() == movieID)
break;
}
return selMovieByIndex(index);
}
public Movie selMovieByIndex(int index) {
return movieList.get(index);
}
public void loadMovieList()
{
//loads through text file
addMovieToList(new Movie(tempMovie));
System.out.println("Movie Database loaded");
}
public class Movie{
private int movieID;
private String movieName;
private int movieDuration; //in minutes;
private String movieRating; //G; PG; PG13; NC16; M18; R21;
private boolean has3D;
private boolean status;
}
If you have a class that depends on a NameLibrary, you should inject it via the constructor or a set method.
Firstly, its difficult to assess what issues you truly have without any code to show us.
However you mention main method, as in
public static void main(String args[]){};
this main method is designed specifically to run the application, your compiler needs that specific method, it is not designed to be used as an accessor method
e.g.
public int getValue(){
return value;}
this is not the only reason you can't access the main method variable. main doesn't have a return type (due to the use of void) plus the idea of SCOPE (each method has a scope, any method that contains a variable can see that variable, but nothing outside of it can directly see it without a return type) you use scope to limit what can be accessed or what cannot be accessed outside of the methods or classes (thats why class variables usually will have private, in order to limit accessibility)
Create a getter-method which returns the list inside your NameLibrary. if your other class extends from NameLibrary you can call this getter-method with the object reference to your NameLibrary class.
If you want int x to be accessible from other classes, you write:
public class myClass{
public int x = 0;
}
To access it from other classes, you simply write:
myClass.x ... (do something)

Change value from another form java

I have a main form (RandomSend) and another form called (_user)
in the randomsend form I declare a public static variable:
public class RandomSend extends javax.swing.JFrame {
......
public static String userGender; // this variable I want to change from another form (_user)
....
}
and in the RandomSend class I declared _user instance that try to change userGender value
_user setGender = new _user();
setGender.setModalExclusionType(ModalExclusionType.APPLICATION_EXCLUDE);
setGender.setAlwaysOnTop(true);
setGender.setVisible(true);
In the _user form (class) I trying to change userGender vale:
public class _user extends javax.swing.JFrame {......
....
RandomSend.userGender="male";
....}
when I check the value from within _user , the value of RandomSend.userGender is "male"
but from my main form the value is null...
new new
My attempt According to answer number 1
public class RandomSend extends javax.swing.JFrame {
/**
*
*/
private static String userGender;
.....
.....
// show dialogbox to select gender...
_user setGender = new _user();
setGender.setModalExclusionType(ModalExclusionType.APPLICATION_EXCLUDE);
setGender.setAlwaysOnTop(true);
setGender.setVisible(true);
....
....
// setter
public static void setUserGender(String gender)
{
if(gender.toLowerCase().equals("female") ||gender.toLowerCase().equals("male"))
userGender = gender;
else userGender= "Unknown!!";
}
//getter
public static String getUserGender()
{
return userGender;
}
and in the other class (frame) :
public class _user extends javax.swing.JFrame {
....
....
RandomSend.setUserGender("male");
..
..
..
}
but the Randomsend.userGender doesn't change!
You make changes to an objects member values via the use of getter and setter functions that you define on that object. To use your example you'd end up with something like:
public class RandomSend extend javax.swing.JFrame {
// This should be preferred for values that can mutate (non-final) to prevent
// modification without the owning class being alerted the value is changing
private static String userGender;
public static void setUserGender(String value) {
userGender = value;
}
public static String getUserGender() {
return userGender;
}
}
Using this example you would change the value by calling RandomSend.setUserGender("male") and you would read this value by calling RandomSend.getUserGender().
Some Additional Notes
I just wanted to point out some additional things that I noticed about your sample. Using static values in the manner that you are is not necessarily the best idea. You're locking the use of the class down in the wrong way. You should maintain an instance of a User class or some other kind of class that manages information specific to a user, such as gender. By managing an instance instead of static values on a class you're making it easier for you to handle other users within the application if that need ever rose up. If you are sure you never need to support more than the current user, then you can still use instances but implement it with a singleton pattern.
That would look something like:
public class SingletonExample {
private static SingletonExample instance = null;
// Declared private to prevent new SingletonExample
// outside of this class
private SingletonExample {}
public static SingletonExample getInstance() {
if (instance == null) {
instance = new SingletonExample();
}
return instance;
}
}
You would use this class by fetching an instance like SingletonExample.getInstance() and then operate on that instance. Using this methods guarantees that in all points in your project you're accessing the same instance of the same object making "global" in a sense.
Another note I would like to make is try and use final values or better yet, an enum instead of strings for things like gender which you will most likely use as values. I say this because in order to properly compare genders you have to do:
if (RandomSend.userGender.equals("male")) {
// ...
}
If you instead created a Gender class with constants like:
public Gender {
public static final int MALE = 1;
public static final int FEMALE = 2;
}
And comparisons (provided value changes in the proper classes)
if (RandomSend.userGender == Gender.MALE) {
// ...
}
And no more wasted string literals being passed around. This is such a good idea that Java has an entire construct unique to providing this solution called enums. You would define a Gender enum like so:
public enum Gender {
MALE,
FEMALE;
}
And then you declare you userGender as a Gender value and your comparisons are the same as if you built the enum yourself from a class with constant values. These changes can, in the long run, make your projects more manageable and easier to maintain.

Categories