Private and Public variables in a method Java - java

Say I have a class that uses multiple ArrayLists:
public static ArrayList<String> openable = new ArrayList<>();
public static ArrayList<String> commands = new ArrayList<>();
public static ArrayList<String> mail = new ArrayList<>();
public static ArrayList<String> mailCommands = new ArrayList<>();
public static ArrayList<String> previousCommands = new ArrayList<>();
And I have multiple other classes that contain methods that use those ArrayLists. Say I also have a class called connect, that extends this first class containing those variable:
public class Connect extends Main_Menu{
If I were to call the methods that I usually call in the Main_Menu class, from the Connect class using new variables with the same name that are private:
private static ArrayList<String> previousCommands = new ArrayList<String>();
private static ArrayList<String> openable = new ArrayList<>();
private static ArrayList<String> commands = new ArrayList<>();
private static ArrayList<String> mail = new ArrayList<>();
private static ArrayList<String> mailCommands = new ArrayList<>();
Would the method using these ArrayLists use the data from the public variables in the Main_Menu class or would it use the private data from the variables in the Connect class?

see for yourself:
static class Parent
{
public static int A = 5;
public static int B = 18;
public static int getA(){
return A;
}
public static int getB(){
return B;
}
}
static class Child extends Parent
{
private static int A = 10;
public static int getA(){
return A;
}
}
public static void main(String[] args) {
Parent p = new Parent();
Child c = new Child();
System.out.println("Parent A: " + p.getA());
System.out.println("Parent B: " + p.getB());
System.out.println("Child A: " + c.getA());
}
output:
run:
Parent A: 5
Parent B: 18
Child A: 10
BUILD SUCCESSFUL (total time: 0 seconds)

I suppose that the static fields in the Connect class are merely overriding the visibility of the same fields in the Main_Menu class. Outside of the scope of the Connect class, the field is not visible, and so you can't access it. You would get an exception if you could even compile at all.
Edit: I am assuming that you are accessing these static variables directly, and not accessing private fields through overridden methods as suggested by other users.
Main.java:
public class Main {
public static ArrayList<String> things = new ArrayList<>();
public static void main(String[] args){
Playground.things; // <- Cannot access private static field outside of that class
}
}
Playground.java:
public class Playground extends Main {
private static ArrayList<String> things = new ArrayList<>();
}

Related

ArrayList empty

I think it's a simple question but keeps me from moving forward in the project. Why, when I use the ArrayList as a reference from a class to another, it is empty?
public class FirstClass {
private ArrayList<String> myList = new ArrayList<>();
public ArrayList<String> getMyList() {
return myList;
}
public static void main(String[] args) {
FirstClass fc = new FirstClass();
fc.getMyList().add("Test");
System.out.println(fc.getMyList());
}
}
Output when I run FirstClass.main:
[Test]
public class OtherClass {
FirstClass csv = new FirstClass();
public ArrayList<String> otherList = csv.getMyList();
public static void main(String[] args) {
OtherClass oc = new OtherClass();
System.out.println(oc.otherList);
}
}
Output when running the OtherClass.main:
[]
I've Googled so many time and the solutions that I found are not working. I followed step by step, creating a getter method in the class that is populating the ArrayList, use the method to populate it, use the print method to make sure the array is populated at the end of the main method. All good, ArrayList is full and ready to be used but when used as reference is empty.
Because a new instance of FirstClass is being created inside of OtherClass, otherList in OtherClass is empty.
The ArrayList that oc.otherList refers to is different from the one that you populated for FirstClass in the main method.
You can edit your OtherClass to work:
public class OtherClass {
private FirstClass csv;
public ArrayList<String> otherList;
public OtherClass(FirstClass fc) {
this.csv = fc;
this.otherList = fc.getMyList();
}
public static void main(String[] args) {
FirstClass fc = new FirstClass();
fc.getMyList().add("Test");
OtherClass oc = new OtherClass(fc);
System.out.println(oc.otherList);
}
}
OtherClass creates the FirstClass without FirstClass main method, so it does not add() to the list.
You can do something like below.
public class FirstClass {
private List<String> myList;
// Instance block: will executed the moment you create object
// of FirstClass
{
myList = new ArrayList<>();
myList.add("Test String");
}
public List<String> getMyList() {
return myList;
}
}
public class OtherClass {
private static List<String> otherList;
public static void main(String[] args) {
FirstClass fc = new FirstClass();
otherList = fc.getMyList();
System.out.println(otherList); //iterate if want to check specific elements in the list
}
}
Or a better way would be to create a method which will add elements to the list and read it in the otherclass by calling the method using firstclass's object.

Whats the best pratice to create constant variables and subclasses inhertience them

I am not sure if there is a standard or good practice to create the constant variables in the parent class, and then subclasses reuse.
public class parentA{
protected static final String name = Constants.SYS_NAME;
protected static final String code = Constants.CODE;
}
public class son extends parentA{
private static void main(String[] args)
{
System.out.println("Name: "+name);
System.out.println("Code: "+code );
}
}
A common practice is to use an interface for constants.
interface MyInterface {
public static final int X = 10;
public static final int Y = 20;
}
public class Main {
public static void main(String[] args) {
System.out.println(MyInterface.X);
}
}
Output:
10

Calling static variable from another static variable constructor

In my Android application I have to initialize a lot of static Objects before the first Activity starts. From what I know, static variables are initialized when classes are loaded. So, with time the amount of static objects in project began to grow and now I'm getting NullPointerExceptions. In my case static objects may call other static objects in their constructors. So my question is: could some static variables be initialized before variables they depend on and thus cause NullPointersExceptions? Is that possible?
Code example :
private static class HardwareManagersHolder implements HardwareManagers, IManagers {
private final AtomicBoolean senderAcquire = new AtomicBoolean(false);
private final AtomicInteger receiverAcquire = new AtomicInteger(0);
public IAudioManager audioManager;
public IVideoManager videoManager;
public IVibrationManager vibrationManager;
public IBatteryHelper batteryHelper;
#Override
public void configureManager() {
audioManager = AudioHelper.getInstance();
vibrationManager = VibrationManager.getInstance();
videoManager = VideoManager.getInstance();
batteryHelper = BatteryHelper.getInstance();
}
And an Object Holder:
public class VideoManager implements IVideoManager {
private static class VideoManagerHolder {
public static final VideoManager VIDEO_MANAGER_INSTANCE = new VideoManager();
}
public static VideoManager getInstance() {
return VideoManagerHolder.VIDEO_MANAGER_INSTANCE;
}
}
I tried to reconstruct your exception with the snippets you provided. I used the following code:
public interface IVideoManager {}
public class VideoManager implements IVideoManager {
private static class HardwareManagersHolder {
public IVideoManager videoManager;
public void configureManager() {
videoManager = VideoManager.getInstance();
}
}
private static class VideoManagerHolder {
public static final VideoManager VIDEO_MANAGER_INSTANCE = new VideoManager();
}
public static VideoManager getInstance() {
return VideoManagerHolder.VIDEO_MANAGER_INSTANCE;
}
public static void main(String[] arg) {
System.out.println("Start test");
HardwareManagersHolder h = new HardwareManagersHolder();
h.configureManager();
if (h.videoManager == null) {
System.out.println("VideoManager is null");
}
System.out.println("Test finished");
}
}
This code works on my machine. If this code is not working on yours, there is some other fault.
Are you initializing them in a static constructor? They would get called first for precisely this reason.
static
{
VIDEO_MANAGER_INSTANCE = new VideoManager();
}

Calling an ArrayList of Strings to another class?

Am I doing this correctly?
test.java (MAIN):
public class test {
public static ArrayList<String> testArray = new ArrayList<String>();
public static void main (String[] args) {
ArrayList<String> test = new ArrayList<String>();
test.add("blah1");
test.add("blah2");
}
public static ArrayList<String> passTestArray() {
return testArray;
}
}
secondClass.java
public class secondClass {
ArrayList<String> test = test.passTestArray();
for (int i = 0; i < test.size(); i++) {
System.out.println(authors.get(i));
}
}
Getting nothing as an output from the secondClass class. Not sure if I'm doing this correctly or not. :/
In secondClass.java, you're creating a new ArrayList and then trying to call a method on it that doesn't exist. You'll need to do something more like the below to initialize your test class and call its methods.
public class SecondClass {
private Test firstClass;
private ArrayList<String> test = new ArrayList<String>();
SecondClass() {
firstClass = new Test();
test = firstClass.passTestArray();
}
}
In the above, you'll be creating the secondClass.java, initializing your first class (test.java), and then calling its methods.

Why couldn't I deal with argument in java?

I'm java virgin. I've made really simple code like below.
class TreeData implements Comparable<TreeData> {
private String sixString;
private ArrayList<Integer> stringNum = new ArrayList<Integer>();
private ArrayList<Integer> charNum = new ArrayList<Integer>();
public TreeData(String sixString, int stringNum, int charNum){
this.sixString = sixString;
(this.stringNum).add(stringNum);
(this.charNum).add(charNum);
}
public int compareTo(TreeData other) {
return sixString.compareTo(other.getSixString());
}
public String getSixString(){
return sixString;
}
}
class Child<T extends Comparable<T>>{
public void print(T data){
//error : String a = data.getSixString();
System.out.println("hi");
}
}
public class Test {
public static void main(String[] args) {
Child<TreeData> child = new Child<TreeData>();
TreeData td = new TreeData("sixString", 8, 2);
child.print(td);
}
}
I had a problem in 'print' method in the Child class. When I tried calling the getSixString() method of data(passed as argument), it occurs error. I don't know why I can't using public method in the argument 'data'. Is it related with Generic? Thanks, in advance.
In your Child class, you only define T to be extending Comparable. Yet you expect it to have the method getSixString which Comparable doesn't have. What you probably want it for it to be extending TreeData:
class Child<T extends TreeData>{
public void print(T data){
String a = data.getSixString();
//should work now since T defines getSixString()
}
}
Or better yet if all you want is for T to be TreeData, you don't need any generic class. I'm assuming your real intention was:
class Child extends TreeData {
public void print(){
String a = getSixString();
}
}

Categories

Resources