Accessing instance methods that are two objects deep in Java - java

Say I have a class, Bobject with an instance variable and method to retrieve it:
public class Bobject {
private int bInstVar;
public Bobject() {
bInstVar = 1;
}
getBInstVar() {
return bInstVar;
}
}
If I create a class Cobject representing an object that is an array of Bobject like so:
public class Cobject {
public Bobject[] cInstVar;
public Cobject() {
cInstVar = new Bobject[2]; //arbitrary array size for simplicity of the question
for (i = 0; i <= 2; i++;) {
cInstVar[i] = new Bobject();
}
}
}
If I have a main program that creates a Cobject and attempts to access methods of the references to the Bobjects stored in each element, I find that I have to first access the Cobject instance variable, cInstVar. This means cInstVar has to be public for main() to get at it without a method if main is outside of the package or class.
My question is, is there a way around doing this:?
Cobject c = new Cobject;
c.cObject1[0].getBInstVar();
Instead, I want to have an object that is an array of another class and get to that classes instance methods easier like so:
Cobject c = new Cobject;
c.getBInstVar(); // error says 'array required, but Cobject found'
I'm still pretty new to Java (and stackExchange) so please forgive me if anything I've presented is unclear. Thanks in advance!

As a general rule of thumb class variable should be declared as private and you should use getter and settle methods....
Meaning you will need to create a getter method in 'Cobject' to get the 'Bobject' object your after.... Then another getter/setter method to access any attributes there, or a method to manipulate any data
But yes, you could hard code a method that will go into the array and return what you ask for. Probably need an index parameter tho

you can create a getter method for Bobject[] in Cobject class
and then you can do c.getCObject1()[0].getBInstVar();

Related

How to call an entire class from another class in Java?

I am a beginner in Java. I have two packages in my current project. Each of the packages have two classes called the "packageClassOne" and "packageClassTwo".
The packageClassTwo has a constructor and other public methods.
I want to call the PackageClassTwo from an if statment located in the PackageClassOne. My code looks something like this
packageClassOne:
public class packageClassOne {
public void selectComponent(boolen) {
if(/* check condition*) {
packageClassTwo value = new packageClassTwo();
}
}
}
packageClassTwo:
public class packageClassTwo {
public packageClassTwo(String name){ //Constructor
int length = name.length();
}
public String CreateWord(){
/*functionality ofthis method*/
}
public String CreateSentence(){
/*functionality ofthis method*/
}
}
The problem is that everytime I call the packageClassTwo from my packageClassOne it tries to call the constructor instead of calling the class itself. I want to call the entire packageClassTwo instead of just the constructor.
Can somebody help me please? Thank you in advance for your help
Since Java is an object oriented language, you have to have a mindset of dealing with instances that are realizations of the classes you defined. These are the objects.
So if you want to call a method from packageClassTwo class, you first create an object of packageClassTwo. You seem to be trying to do just this. Once you have the object, you can call its methods. For example
//Instantiate an object by calling the constructor
packageClassTwo object = new packageClassTwo(string);
//Now call its methods
String val = object.CreateWord()
There is no such thing as "calling a class". You call methods of objects of a class.
Occasionally, there might be a well founded need to call methods of a class without initializing objects. Look into static methods and classes for further reading.
If you want to call all methods of packageClassTwo you have to do it explicitly
packageClassTwo pct = new packageClassTwo("");
pct.CreateWord();
pct.CreateSentence();
If you allways want the 2 methods to be called when you create a new packageClassTwo object, than you can just add the calls to the constructor
public packageClassTwo(String name) {
int length = name.length();
pct.CreateWord();
pct.CreateSentence();
}
Edit:
Note that in the second case, if you end up only calling the 2 methods from inside the constructor, it is better to make them private.
As a sidenote, it is a general convention in java to have class names start with a upper case letter : PackageClassTwo not packageClassTwo, and method names to start with lower case createWord not CreateWord. This wll make your code more readable.
If you want to call all the methods from the packageClassTwo, call them from the packageClassTwo constructor
public packageClassTwo(String name)
{
int length = name.length();
CreateWorld();
CreateSentence();
}
I don't think your code will run without compiling errors.because you did not declare the constructor packageClassTwo().

How to use a Get method in java

A ton of questions have been asked on how to create getter and setter methods in java. But i have yet to see one that actually tells me how to use it.
Say i have Private int i = 1; in class A and i want to access it in class B.
I would first create a get method in class A called getIntI(); which would return the value of i.
Then in class B if i wanted to create an if statement that would need the value of i how would I get int i's value. The following is my try and calling the get method which does not work.
if(getIntI == 1)
{System.out.print.ln("int i is one");}
It is probably a really stupid question but i cant find an answer for it elsewhere.
In class A:
public int getIntI(){
return i;
}
Note: Now since your variable is single character named (just I), getter method is named getIntI since the name getI makes lesser sense. But generally, getter methods are something like get+VariableName and do not involve mentioning type. For example if I had a variable called int count, my method would be named getCount instead of getIntCount. Thats the general convention.
Also, naming variables in single char formats (like x, y etc) is discouraged because it may create confusion and management difficulty in complex programs. Though in very small programs they are fine.
Moving back to topic, if you want to access method getIntI() in class B, you will either have to inherit class A or create an object of class A reference to its method.
For class B:
Creating object
A obj = new A();
if(obj.getIntI() == 1)
// Do stuff
Inheriting class A:
public class B extends A{
... // Your stuff
if(getIntI() == 1)
// Do stuff
... // Your stuff
}
Of course there are other ways but these are simpler ones.
if class B extends class A then do only this changes,
if(getIntI() == 1)
If above inheritance was not there then do this,
if(new A().getIntI() == 1)
The problem is that you need to create a object derived from class A before you can access its variables/methods using
A a = new A();
where "a" is the name of the object. Then you can access the getter method by calling a.getIntI. You can also declare the int variable as static so that you wouldn't have to instantiate any objects. An example of class A with the static variable and getter method would be:
public class A {
private static int i = 1;
public static int getIntI() {
return i;
}
}
With this, you can call the getter method with A.getIntI().
First, if you want to access one of A's non-static methods (in this case, getIntI), you need an instance of A, or you can just declare it static.
Secondly, A method call needs a parameter list, even an empty one is needed. getIntI does not need any parameters, so you should add () at the end.
Now, you can get an instance of A somewhere and call it aObj. Andd then you can use it in the if statement:
if (aObj.getIntI == 1)
And remember to add ()!
if (aObj.getIntI() == 1)
Alternatively, you can declare i in A as static. There are two main differences between a static and a non-static variable.
You don't need an instance of the declaring class to access the static variable.
Unlike non-static variables, there is only one static variable. If you have a non-static variable i, you can create lots of instances of A and each instance will have its own i
Now let's see this in action, declare i as static:
public class A {
private static int i = 1;
public static int getIntI () { return i; }
}
Note how both i and getIntI are declared static.
Then you can use in a if statement like this:
if (A.getIntI() == 1)
Note how I use the class name A to access the method, not an instance of A.

Keeping track of all instances of a subclass in the superclass

I have the following, stripped-down Java code:
// Class, in it's own file
import java.util.*;
public class Superclass {
protected List<Subclass> instances = new ArrayList<>();
public class Subclass extends Superclass {
private int someField;
public Subclass(int someValue) {
this.someField = someValue;
updateSuperclass();
}
private void updateSuperclass() {
super.instances.add(this);
}
}
}
// Implementation, somewhere else, everything has been imported properly
Superclass big = new Superclass();
Subclass little1 = big.new Subclass(1);
Subclass little2 = big.new Subclass(2);
Subclass little3 = big.new Subclass(3);
I want to implement a method in Superclass to do something with all the Subclasses. When a Subclass is created, it should add itself to a list in Superclass, but whenever I try to loop through that list in Superclass, it says the size is 1. The first element in the list (instances.get(0)) just spits out a String with all the proper information, but not in object form, and not separately. It's like every time I go to add to the list, it gets appended to the first (or zeroeth) element in String form.
How can I solve this so I can maintain an ArrayList of Subclasses to later loop over and run methods from? I'm definitely a beginner at Java, which doesn't help my case.
If all you need is a count then I suggest a static value that is updated in the constructor of the parent class.
private static int instanceCount = 0;
public Constructor() {
instanceCount++;
}
If you absolutely need every instance in a list so you can do something with them then I recommend you strongly re-consider your design.
You can always create a utility class that will let you maintain the list of objects to run processes on. It's more "Object Oriented" that way. You can also create one class that has all of the operations and then a simpler bean class that has only the data values.
But, if you insist, you can still use the same technique.
private static List<SuperClass> list = new LinkedList<SuperClass>;
public Constructor() {
list.add(this)
}
Each instance gets its own copy of your superclass's variables.
What you want to do is make the variable "static" by putting the static keyword before it. You probably don't even need the superclass accomplish what you're trying to do.

No parentheses in java

I am learning Java and I have learned that methods use parentheses for passing parameters. However, I have also noticed that sometimes I see code which to me looks like a method but it does not have parentheses.
MyObject.something()
MyObject.somethingElse
Where somethingElse does not have parentheses. I assume this is similar to how an arrayList has the size method for getting its size:
myList.size()
whereas an array has length to get its size, which does not have parentheses:
myArray.length
Is my assumption correct? If not, what is the difference?
This is probably an elementary question, but because of the amount of words I need to explain this problem, I have had trouble searching for it.
somethingElse is a property (data member), not a method. No code in the class is run when you access that member, unlike with a method where code in the class is run.
Here's an example:
public class Foo {
public int bar;
public Foo() {
this.bar = 42;
}
public int getBlarg() {
// code here runs when you call this method
return 67;
}
}
If you create a Foo object:
Foo f = new Foo();
...you can access the property bar without parens:
System.out.println(f.bar); // "42"
...and you can call the method getBlarg using parens:
System.out.println(f.getBlarg()); // "67"
When you call getBlarg, the code in the getBlarg method runs. This is fundamentally different from accessing the data member foo.
it is a class field which isn't a private field (usually it can be protected,package or public), so you can take it straight from your class. Usually fields are private, so you cannot take it like this outside your class definition.
myList.size() call a method defined in list class (public defined)
myArray.length call a property in array class not method
public class MyClass{
public int length;
public int size(){
....
}
}
MyClass mc =new MyClass();
mc.length;
mc.size();
This is triggering method called something of the instantiated object called someObject.
someObject.something();
This is accessing a property of the object called someObject (property which is public, most probably).
someObject.name

Accesing a method from another class file?

I need to acces a variable (an int) from another class file. How would I do this? It's a public int, I need to get the int value and put it into a file.
If you have an instance:
AnotherClass another = new AnotherClass();
Then if the field (instance variable) is public:
another.someField;
or if you have a getter method
another.getSomeField();
If none of these is true - add a getter method (this is the preferred way to access instance variables).
If you can't change the class - as a last resort you can use reflection.
Example:
MyClass myclass = new MyClass();
System.out.print(myclass.myint)
Best practice code states that if the variable is not a Static Final, then you should create getters & setters inside the class:
public class Main{
int variableName;
public int getVariableName(){
return this.variableName;
}
public setVariableName(int variableName){
this.variableName = variableName;
}
}
If you want to acess it from another class file then you have to instantiate an Object and then access it using the public method:
Main m = new Main();
int a = m.getVariableName();
Hope it helps.
If you have an instance of that other class, you access it as {instance}.varable.
That varaiable need to either be public, or it needs to be in the same package and not private, or it must be a protected variable in a superclass.
If the variable is static, then you don't need an instance of that class, you would access it like {ClassName}.variable.
Far and away the best thing to do here would be to make the int you need to access a Property of the other class and then access it with a 'getter' method.
Basically, in the other class, do this:
public int Number
{
get
{
return number;
}
set
{
number = value;
}
}
private int number;
Doing this allows you to easily set that in to something else if you need to or to get it's current value. To do this, create an instance of the "AnotherClass" as Bozho already explained.

Categories

Resources