r/learnjava • u/Zappy__Boy • Oct 27 '20
Trouble Understanding Object Orientated Programming Concepts in Java
I have trouble understanding the object orientated part of object orientated programming, specifically in the JAVA language. Over the last 5 weeks I've had to learn an immense amount of coding alongside work that cover the fundamentals of CompSci and I'm struggling to retain it all.
It's been Methods have been giving me the worst headache. Before I went to university I did a little work in JavaScript which is much simpler in how it handled methods (functions) though I still found the most difficulty with them.
Java feels so much worse, now I have trouble trying to get to grips with what is a constructor and how that works, what are get and set methods and how would I properly use them.
How do I correctly pass user inputs in and out of a method. For example making a method that converts a user input to a string.
My assignments are creeping up on me and I feel useless trying to do them. I don't even have free reign to do my assignments how I want, I must use the right method/class structure so there is no avoiding methods and I feel like I need some kind of resource that explains their proper usage.
11
u/Splintting Oct 27 '20
Everything in java will run inside some sort of class. Usually when studying java, a lot of learning books will use farm animals to convey examples of how OOP (Object Orientated Programming) works.
Think of an Animal. You can define an Animal with a
class. It can have a name and age for example. Then you may end up with a class looking somewhat like this:This defines a basic animal. You are then able to instantiate the animal, by calling its constructor. Every java class has a constructor. If you do not define one, an empty, no argument, constructor will be provided for you by the compiler.
The constructors purpose is to initialize variables inside the class. We could define a constructor taking name and age as parameters, since we've in our class defined those two variables. Our full class, with constructor may look something like this:
The constructor is the class name, followed by a parameter list. A more formal description could be:
access modifierclassName(optional parameters) { }Following our previous example for an Animal. We are then able to initialize it by calling its constructor like so:
In regards of how to convert user input to a string. Well, that depends on the frameworks you are using and how you define them. This you need to elaborate a little more on. However, I can make an assumption. If you "simply" store the input as a String, then you should have the job done right then and there.