#Can you instantiate objects within a method, and access info with another method?
1 messages · Page 1 of 1 (latest)
<@&987246399047479336> please have a look, thanks.
While you are waiting for getting help, here are some tips to improve your experience:
If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.
Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.
So, let'S say I have a main, and two methods which take no parameters. Can I instantiate objects within the first method, and then show info about those objects in the second method, and none of those methods can take any parameters?
Is this possible?
you mean smth like this:
public class MyClass {
public static void main(String[] args) {
TestClass test = new TestClass();
}
private static void methodOne() {
// use test in here without parameter
}
}
no, i mean something like main --- method1 for creating objects ---- method2 for showing info about those objects created in the first method
you could store them as fields so there are available in the second method
if the second method is in a different class make getters
No, the main, and the two other methods are within the same file
and the class for creating objcets is within a file of itself
public class MyClass {
private static TestClass test;
public static void main(String[] args) {
methodOne();
methodTwo();
}
private static void methodOne() {
test = new TestClass();
}
private static void methodTwo() {
// use test here
}
}
this would be an example in static context ^
pls show your code
without its hard to help
how do you post code here
read this ^
`
public static void main(String[] args) {
Livre premier, second, troisieme, quatrieme, cinquieme, sixieme;
init();
afficher();
}
public static Livre init() {
Livre premier = new Livre("Architectures réparties en Java", "Annick Fron", 9);
/**Livre second = new Livre("Programmer en Java", "Claude DELANNOY", 300);
Livre troisieme = new Livre("Apache Maven", "Nicolas de Loof", 245);
Livre quatrieme = new Livre("Japprend Java", "Jena Moyen", 400);
Livre cinquieme = new Livre("Japprend Quekchose", "Non au oui", 600);
Livre sixieme = new Livre("Il le faut bien", "Oui au non", 700);**/
return premier;
}
public static void afficher() {
System.out.println(premier.afficher());
System.out.println(second.afficher());
System.out.println(troisieme.afficher());
}
}```
Detected code, here are some useful tools:
public class Biblio {
public static void main(String[] args) {
Livre premier, second, troisieme, quatrieme, cinquieme, sixieme;
init();
afficher();
}
public static Livre init() {
Livre premier = new Livre("Architectures réparties en Java", "Annick Fron", 9);
/**Livre second = new Livre("Programmer en Java", "Claude DELANNOY", 300);
Livre troisieme = new Livre("Apache Maven", "Nicolas de Loof", 245);
Livre quatrieme = new Livre("Japprend Java", "Jena Moyen", 400);
Livre cinquieme = new Livre("Japprend Quekchose", "Non au oui", 600);
Livre sixieme = new Livre("Il le faut bien", "Oui au non", 700);**/
return premier;
}
public static void afficher() {
System.out.println(premier.afficher());
System.out.println(second.afficher());
System.out.println(troisieme.afficher());
}
}
so in the main, I call two methods, the first to create the objects, the second to show info about those objects
as said, I would just store them as fields
sorry, waht do you mean?
and what does this line do exactly?
just stores the variable but on a higher level
anything which I could read about this?
@high axle It does not work, it looks like after I create my objects within the method, and return to main, the objects are only lcoated within the method in which they were created
what did you change?
yeah but you dont save them in the fields
you create new variables
with the same name
in you init method
remove the type on the left side
ok it works now. Please, can you show me documentation as to what did I even just do?
I liked the article you showed me last time, it cleared much for me
you know what fields are?
They are varaibles I guess?
yeah basically, fields are just variables inside a class
but outside a method
so basically:
public class Employee {
private String name; // example field
}
this way its available in "all" methods inside employee available
you know about access modifier like private, public, protected?
yes recently learned about them. Why is it we put the varaibles in private here?
its not needed, it also could be public etc
but in Java the accessibility should be as low as possible
ah ok it's just a convention so as to not mix stuff with each other
to be on safer side
yeah exactly
Item 15: Minimize the accessibility of classes and members
The single most important factor that distinguishes a well-designed component
from a poorly designed one is the degree to which the component hides its internal
data and other implementation details from other components. A well-designed
component hides all its implementation details, cleanly separating its API from its
implementation. Components then communicate only through their APIs and are
oblivious to each others’ inner workings. This concept, known as information
hiding or encapsulation, is a fundamental tenet of software design [Parnas72].
ok, let me reformulate if I understood correctly : my error was that I was declaring objects within a method, and since I could not return those objects, they were essentially stuck within this method only, correct?
yeah
The rule of thumb is simple: make each class or member as inaccessible as
possible. In other words, use the lowest possible access level consistent with the
proper functioning of the software that you are writing.
ok, and declaring my objects inside my main method means that my objects would have been stuck in the main only...
correct?
yeah as long as you dont pass them to other method or classes etc
ok, and if we want my variables to be seen as far and wide as possible, I declared my variables as variables of the class instead, thus meaning that any method, whether main, method, function or else, can access theM?
public class Test {
public static void main(String[] args) { // the variable name is only accessable in this ...
String name = "SquidXTV";
} ... // method, an indicator is also these {} parentheses
}
yeah, note that if you make the field public other classes outside can access it
ok, so this is exactly the same thing as when we declare fields/variables in classes for objects bro
what do you mean with that exactly?
you mean if we have non static variables?
exactly
fields are kinda just data of a class
ok, last question on this subject (i love you for being so clear and patient, really do) : I read the link you gave me about static stuff : something static means that the variable/method is used by the class, and not by objects
here, putting the variables as static means we're letting them be used by anyone who is not an object, right?
you mean related to this example?
public class MyClass {
private static TestClass test;
public static void main(String[] args) {
methodOne();
methodTwo();
}
private static void methodOne() {
test = new TestClass();
}
private static void methodTwo() {
// use test here
}
}
yes, the static in the fields
I made the field and two methods static so its easier to call them in the main method as its also static and my guess was that your methods are also static
otherwise you would need to make an isntance of the same class to use the test variable
also not sure if this is a task for school or smth but I think this is not good structure of your program
brah, i already told you my teacher sucks so bad
like, you already did 1000 times more than this person
i consider you more my teacher than this perosn
I would instead make a class called Main and a class called Biblio which only have a constructor and a method called afficher
then put the init method stuff inside the constructor. A constructor is basically an initialization of a class. this way its also guaranteed that
the fields are initialized.
then create an instance of Biblio in your main method and use it there. This way you also have no problems with static and can make the Biblio stuff
all non static
yes, God knows what she even thinks
🤷♂️
But based on our understanding of static stuff, static means anyone in the class who is not an object can use this stuff, no? So, by declaring our variables as static, we're also saying that the methods, which are also static, can use them? Is this a good understanding of what is happenign?
here maybe for a better understanding of static:
The keyword static controls ownership (not accessibility). A method or field that is static belongs to the class instead of an instance of a class. Suppose there is a simple class called Person:
class Person {
String name;
Person(String name) {
this.name = name;
}
String getName() {
return name;
}
}
Now, you can create as many instances of this class as you want:
Person first = new Person("John");
Person second = new Person("Jane");
And each person has his own name, because it is non-static. So we can do
System.out.println(second.getName()); // prints Jane
In total, since there exist 2 instances of the Person class now, we also have 2 names and also 2 getName() methods. Each belonging to its corresponding instance of the class.
Now, if something is static, it belongs to the class and not to instances of it. While we just created 2 instances of Person, there exists exactly one class Person itself. So if we write:
class Person {
static int amountOfEyes = 2;
String name;
Person(String name) {
this.name = name;
}
String getName() {
return name;
}
}
Then amountOfEyes belongs to the Person class, not to the instances we created. As a result, there exist in total 2 names, 2 getName() methods but only one amountOfEyes variable.
As such, we also access this variable through the class, not through instances of it:
// Like this
System.out.println(Person.amountOfEyes);
So neither first nor second nor third have their own amountOfEyes. There is only one amountOfEyes and it belongs to the Person class itself.
To summarize, static things belong to the class, there is only one class no matter how many instances you create of it. Non-static things belong to instances of a class, each instance has its own set of non-static fields and methods.
yeah
and in this example the name field is non static that means each individual Person has its own name
if I created them as fields of an object, I could create several "premier", "second", etc.
you would still have only one of them in an instance, but each instance got its own fields
so if there are non static and you create two Biblio instances then you got 2 different premier, second... instances
wait, can you give me an example of having two biblio instances?
ok so imagine your current Biblio implementation
and then this one:
// Main.java
public class Main {
public static void main(String[] args) {
Biblio biblioOne = new Biblio();
biblioOne.afficher();
Biblio biblioTwo = new Biblio();
biblioTwo.afficher();
}
}
// Biblio.java
public class Biblio {
private final Livre premier;
private final Livre second;
private final Livre troisieme;
private final Livre quatrieme;
private final Livre cinquieme;
private final Livre sixieme;
// constructor instead of init method
public Biblio() {
premier = new Livre("Architectures réparties en Java", "Annick Fron", 9);
second = new Livre("Programmer en Java", "Claude DELANNOY", 300);
troisieme = new Livre("Apache Maven", "Nicolas de Loof", 245);
quatrieme = new Livre("Japprend Java", "Jena Moyen", 400);
cinquieme = new Livre("Japprend Quekchose", "Non au oui", 600);
sixieme = new Livre("Il le faut bien", "Oui au non", 700);
}
public void afficher() {
System.out.println(premier.afficher());
System.out.println(second.afficher());
System.out.println(troisieme.afficher());
}
}
// Livre.java
public class Livre {
// ...
}
sorry, I feel bad for making you do this, I think you misunderstood me
I was saying, since those premier, deuxieme, etc. are static, then they are basically limited to one copy of the main class, and not to several like objects which can share several varaibles of the same name
yeah exactly
I have one last question : is it possible to declare an object as an instance of the main class?
Could you do something like this?
yeah its possible to create an Object of the class that holds the main method
tho if you are trying to create the constructor in the picture it needs to be outside the main method
because its a "method" itself
ah yes, you cannot put methods inside methods right
again to static to visualize it:
// Main.java
// Main.java
public class Main {
public static void main(String[] args) {
Biblio biblioOne = new Biblio();
biblioOne.afficher();
Biblio biblioTwo = new Biblio();
biblioTwo.afficher();
}
}
// Biblio.java
class Biblio {
private static int numberOfInstances = 0;
private final Livre premier;
private final Livre second;
private final Livre troisieme;
private final Livre quatrieme;
private final Livre cinquieme;
private final Livre sixieme;
// constructor instead of init method
public Biblio() {
premier = new Livre("Architectures réparties en Java", "Annick Fron", 9);
second = new Livre("Programmer en Java", "Claude DELANNOY", 300);
troisieme = new Livre("Apache Maven", "Nicolas de Loof", 245);
quatrieme = new Livre("Japprend Java", "Jena Moyen", 400);
cinquieme = new Livre("Japprend Quekchose", "Non au oui", 600);
sixieme = new Livre("Il le faut bien", "Oui au non", 700);
numberOfInstances++;
}
public void afficher() {
System.out.println(premier.afficher());
System.out.println(second.afficher());
System.out.println(troisieme.afficher());
}
}
// Livre.java (random implementation because I dont know what afficher means)
class Livre {
private final String titre;
private final String auteur;
private final int nbPage;
Livre(String titre, String auteur, int nbPage) {
this.titre = titre;
this.auteur = auteur;
this.nbPage = nbPage;
}
public String afficher() {
return titre + " | " + auteur + " | " + nbPage;
}
}
using a debugger shows us that each biblio instance has its own non static fields, as we already said
and that they share the numberOfInstances variable because its static
thats basically it
yes, since there exists only one numberOfInstances, it is shared between them
with the same value etc
yeah
you agreed with me here ?
ok, very very last question and Im finished for today
i head it's a bad thing?
heard*
what exactly?
classes inside a class?
but its also said that classes should always have its own file
used if you have many parameter in the constructor
makes it easier to create optional parameter
not that important for you as of now
ah ok
tho you can still change stuff inside the class if they are not final
for example:
public class Main {
public static void main(String[] args) {
final Person person = new Person("Squidxtv");
person = new Person("LearningGeek"); // not working for final variable because it will assign it with a new instance
person.setName("LearningGeek"); // valid, it changes the internal state of the Person but not the variable itself
}
}
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public void setName(String newName) {
this.name = newName;
}
// ...
}
thats why this is also a thing
There are some classes for which immutability is impractical. If a class
cannot be made immutable, limit its mutability as much as possible. Reducing
the number of states in which an object can exist makes it easier to reason about
the object and reduces the likelihood of errors. Therefore, make every field final
unless there is a compelling reason to make it nonfinal.
sorry you lost me with your example
but thats more do's and don'ts about Java, very important to write better code later, although you should learn Java first so not that important for you currently
you prob dont understand much because there is still some stuff missing
but I really recommend reading Effective Java III if you are more intermediate Java, it makes you a better programmer
xD
anyway, my last question for tonight
When you set set and get methods, and correct me if Im wrong, those methods are set up so as to be used outside the class of the object, right?
yeah
if I'm inside the class of my object, I can just use my normal fields, no need to use those methods (it would be useless, since we already have access to the varaibles inside of the class)
yeah
ok, perfect
its just a cleaner/better code practice
yes, because then it would be couner intutive to use methods to acces something whcih you already have
btw, what would you consider to be "intermediate java" level
im just starting to learn OOP
hard to say
i want to become better, what woudl you recommend?
so I assume you are in some kind of uni or smth?
i'm technically one of the "best" student of my class, but this deos not mean much
technical school
more
i had no idea what I wanted to do with my life, and I like computer and programming, and I wanted to do something with this
so i decided on this
so I learned on my own using the mooc.fi course and did some projects to understand these concepts correctly
then just by helping here on the server and getting tips from others here, as well as reading effective java afterwards
OOP concepts are important, so you shoudl really understand:
- Abstraction
- Encapsulation
- Inheritance
- Polymorphism
...
MOOC is a completely free introductory Java course created by the University of Helsinki, it is a great way to learn Java from the ground up.
It consists of two parts, one at beginner, and another at intermediate level. The end of the course is marked by creating your own Asteroids game clone!
Even though the instructions show how to configure and use NetBeans for the course, you can use IntelliJ. To use IntelliJ, simply install the TMC plugin by opening IntelliJ -> File -> Settings -> Plugins and searching for TMC. You will then be able to use IntelliJ to complete MOOC.
Visit MOOC here: https://java-programming.mooc.fi/
(the course is available in both English and Finnish)
About the course - Java Programming
i learned the first two I think ...
and learn the basics there
abstract means to create a general idea of an object
like a rectangle
encapsulation measn to keep eveyrthing in tight units
first for programming its important to understand:
- logic
- syntax
- OOP (for Java specific)
yeah, often used example is an abstract class Animal and then classes like Dog, Cat etc which inherit from Animal as they have something in common
Animal is too general though?
i get the point
but canine for Dogs would make more sense
but you can always generalize bigger and bigger I think
logic would not be a problem form e
for me*
it's the syntax and knowledge which poses a "problem", because I lack experience
yeah always depends on the programs needs
as in, I lack knowledge abotu the language
i know how to reason
but reaosn without knowledge is a problem
reason*
it's the knowledge part which I need to improve
becuse I know very little about java
syntax is just how you would do things in Java specific using its provided keywords
so to be intermediate you should know what all the keywords like for, while, class, final, static etc do
some are easier some are more intermediate
as an example its important to understand the concept of static and how to use it in Java specific
I think I understand it now?
yeah
btw, where is this list of all the articles, i found it very well written
no the static article for example
the one I provided last time?
yes
This beginner Java tutorial describes fundamentals of programming in the Java programming language
official tutorials from oracle
on the left hand side is a list of topics
oh ok i had no idea it was taken from this, makes sense since the website you gave me about the this keyword was very clear
and i understood eveything
wait which one do you mean
im confused xD
you sent me a link https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
This beginner Java tutorial describes fundamentals of programming in the Java programming language
about this
it was very clear
oh yeah, you said static that kinda confused me
this one is more about Objects and classes in general
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/index.html
this one for Java in general
This beginner Java tutorial describes fundamentals of programming in the Java programming language
btw i downloaded the book you suggested
kinda illegal 
for private use obviously
btw, believe it or not
i usually buy books which i appreciate
i buy tons of books and i love reading
I didnt buy it myself xD
i prefer paper
anyway, i need to go, my brain wants to do something else
it seem you're a night owl
i only find you at night
currently xD, my sleeping rhythm is kinda fucked ngl
slept from 2pm till 9pm or smth 💀
yes, you need a better sleep schedule
telling you as someone older than you
who went through this phase
i feel like sh.t when i dont sleep correctly
ayway, bye my friend, and thanks a million times for your help
you'Re one of my favorites here
bye