#Can you instantiate objects within a method, and access info with another method?

1 messages · Page 1 of 1 (latest)

coarse mica
#

is it possible?

spark emberBOT
#

<@&987246399047479336> please have a look, thanks.

spark emberBOT
#

While you are waiting for getting help, here are some tips to improve your experience:

Code is much easier to read if posted with syntax highlighting and proper formatting.

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.

coarse mica
#

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?

high axle
#

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
    }
}
coarse mica
#

no, i mean something like main --- method1 for creating objects ---- method2 for showing info about those objects created in the first method

high axle
#

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

coarse mica
#

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

high axle
#
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 ^

high axle
#

without its hard to help

coarse mica
#

how do you post code here

coarse mica
#

i dont know how to do the little signs on my keyboard

#

oh wait

high axle
#

`

coarse mica
#

    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());
    
}
    
}```
spark emberBOT
# coarse mica ``` public class Biblio { public static void main(String[] args) { ...

Detected code, here are some useful tools:

Formatted code
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());
  }
}
coarse mica
#

so in the main, I call two methods, the first to create the objects, the second to show info about those objects

high axle
coarse mica
#

sorry, waht do you mean?

coarse mica
#

what exactly did you do?

#

i saw the code, not sure of seeing what is happening

high axle
#

this way you can access test in methodTwo without parameter

coarse mica
#

and what does this line do exactly?

high axle
#

just stores the variable but on a higher level

coarse mica
#

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

high axle
#

what did you change?

coarse mica
#

I did what you said,

high axle
#

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

coarse mica
#

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

high axle
#

you know what fields are?

coarse mica
#

They are varaibles I guess?

high axle
#

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?

coarse mica
#

yes recently learned about them. Why is it we put the varaibles in private here?

high axle
#

its not needed, it also could be public etc

#

but in Java the accessibility should be as low as possible

coarse mica
#

ah ok it's just a convention so as to not mix stuff with each other

#

to be on safer side

high axle
#

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].

coarse mica
#

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?

high axle
#

yeah

high axle
coarse mica
#

ok, and declaring my objects inside my main method means that my objects would have been stuck in the main only...

#

correct?

high axle
#

yeah as long as you dont pass them to other method or classes etc

coarse mica
#

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?

high axle
#
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
}
high axle
coarse mica
#

ok, so this is exactly the same thing as when we declare fields/variables in classes for objects bro

high axle
#

you mean if we have non static variables?

coarse mica
#

It's the same thing as doing this when we have a class for objects

high axle
#

exactly

coarse mica
#

the first part

#

with the private variables

high axle
#

fields are kinda just data of a class

coarse mica
#

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?

high axle
#

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
    }
}
coarse mica
#

yes, the static in the fields

high axle
#

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

high axle
coarse mica
#

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

high axle
#

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

coarse mica
#

yes, God knows what she even thinks

high axle
#

🤷‍♂️

coarse mica
high axle
#

here maybe for a better understanding of static:

spark emberBOT
#

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.

coarse mica
#

so in this case,

#

my fields belong to my class, and there are only one of each

high axle
#

yeah

high axle
# spark ember

and in this example the name field is non static that means each individual Person has its own name

coarse mica
#

if I created them as fields of an object, I could create several "premier", "second", etc.

high axle
#

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

coarse mica
#

wait, can you give me an example of having two biblio instances?

high axle
#

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 {
    // ...
}
coarse mica
#

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

high axle
#

yeah exactly

coarse mica
#

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?

high axle
#

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

coarse mica
#

ah yes, you cannot put methods inside methods right

high axle
#

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

coarse mica
#

with the same value etc

high axle
#

yeah

coarse mica
#

there's only one for the class

#

you cannot clone one for each instance

coarse mica
high axle
#

yeah

#

classes inside classes is a thing tho xD

coarse mica
#

ok, very very last question and Im finished for today

#

i head it's a bad thing?

#

heard*

high axle
#

what exactly?

coarse mica
#

classes inside a class?

high axle
#

highly depends

#

Builder are mostly inner classes

coarse mica
#

tbh I have no idea what is a builde

#

builder*

high axle
#

but its also said that classes should always have its own file

coarse mica
#

yes this makes sense

#

it makes it more readable

high axle
#

used if you have many parameter in the constructor

#

makes it easier to create optional parameter

#

not that important for you as of now

coarse mica
#

wait btw what is "final" again?

#

i forgot about this

#

isnt it for constants ?

high axle
#

final just makes a variable a constant

#

so you cant change it anymore

coarse mica
#

ah ok

high axle
#

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.

coarse mica
#

sorry you lost me with your example

high axle
#

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

coarse mica
#

ok

#

i appreciate the effort though

high axle
#

you prob dont understand much because there is still some stuff missing

coarse mica
#

i learned final if I wanted to set a number to some constant

#

one question :

high axle
coarse mica
#

thanks for mentioning it, I was going to ask you how to learn more

#

lol

high axle
#

xD

coarse mica
#

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?

high axle
#

yeah

coarse mica
#

so as to be able to see and get stuff

#

ok

high axle
coarse mica
#

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)

coarse mica
#

ok, perfect

high axle
#

its just a cleaner/better code practice

coarse mica
#

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

high axle
#

hard to say

coarse mica
#

i want to become better, what woudl you recommend?

high axle
#

so I assume you are in some kind of uni or smth?

coarse mica
#

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

high axle
#

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

coarse mica
high axle
spark emberBOT
#

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

high axle
#

tho its also a bit outdated

#

so I would stick to your school

coarse mica
high axle
coarse mica
#

abstract means to create a general idea of an object

#

like a rectangle

#

encapsulation measn to keep eveyrthing in tight units

high axle
#

first for programming its important to understand:

  • logic
  • syntax
  • OOP (for Java specific)
high axle
coarse mica
#

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

high axle
#

yeah always depends on the programs needs

coarse mica
#

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

high axle
#

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

coarse mica
#

I think I understand it now?

high axle
#

yeah

coarse mica
#

btw, where is this list of all the articles, i found it very well written

high axle
coarse mica
#

no the static article for example

high axle
#

the one I provided last time?

coarse mica
#

yes

high axle
#

official tutorials from oracle

#

on the left hand side is a list of topics

coarse mica
#

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

high axle
#

im confused xD

coarse mica
#

about this

#

it was very clear

high axle
#

oh yeah, you said static that kinda confused me

coarse mica
#

yes it'S about another thing

#

when i was confused about it

high axle
coarse mica
#

btw i downloaded the book you suggested

high axle
#

kinda illegal pepekek

coarse mica
#

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

high axle
#

I didnt buy it myself xD

coarse mica
#

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

high axle
#

currently xD, my sleeping rhythm is kinda fucked ngl

#

slept from 2pm till 9pm or smth 💀

coarse mica
#

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

coarse mica
#

bye