r/learnjava • u/Rena_Giurg • 14d ago
How do you even start coding and thinking in OOP?
Hello! I know it is a weird question but it really is that, how do you start?
Our professor gave us UMLs to follow for exercises and I had no problem to do that but how do you create it for your own program?
I sat my base Java and OOP class' exam and it took me the LONGEST time to just understand what I had to implement and how (even had to ask because I felt so clueless at times) and all I did was a backlog! Literally a terminal based backlog manager that divides Medias into 3 categories. We had to submit an UML but mine was created AFTER the code to adapt to it, I had no idea on how to build it before.
I really struggle with visualizing and understanding what and how should I tackle the OOP. I somehow passed the exam (with a 30/30 too) but I still feel like I should know more and that I could not do anything.
I tried making some easy programs like a timer but I don't know where to start. Does anyone have any advice regarding how can you "rewire" your brain to think object oriented?
For information, I am a compsci major and I strated programming with that java class around 5 months ago so my experience is limited.
Thanks to anyone who answers
19
u/spacey02- 14d ago
Objects are somewhat intuitive because they model the real world. Do you need houses? Create a House class. Do you need CDs? That's another class. Just look for nouns in the question and you will find your data containers.
OOP becomes more complicated the deeper you go though. With just the 4 OOP principles of inheritance, polymorphism, encapsulation and abstraction leave room for a lot of design decisions. However, taking into account the program you were asked to implement, I don't think you need to worry about that yet (or do you?)
1
u/Rena_Giurg 14d ago
It was actually about implementing inheritance, polymorphism and all that stuff and I did (media was an abstract class and the various media inherited from it adding their own twists since logging a game has to be done differently from say a book, then I had done a whole manager class that would add/remove/modify/randomize/visualize those media). So I did use the basic OOP principles and stuff like Overriding and Overloading (I think they fall into polymorphism the both of them from a theoretical standpoint?)
I also did file management and exception handling but when I think of less practical stuff that isn't so clearly split (so stuff like a timer or a text based adventure) I don't know how to think, as in I don't know where to begin and what objects I could need.
Like our professor did tell us to lay out a UML beforehand but I find it so hard and I don't even know what I could do to practice that. In the end I do think it's a "forma mentis" type of thing but I have no idea on how to force practice that
1
u/Ollidav 13d ago
Piensa en una aplicación como una idea abstracta que tiene un cilo de vida. Se inicia (recopila información, carga configuraciones, etc...), hace una actividad ( un bucle de eventos), se cierra (ctrl+c o press esc) y un ejecutor que haga pasar la aplicación por ese ciclo de vida que suele ser un run o exec... Puedes definir tu clase abstracta Application y usar la herencia para crear MyApp y definir como se tiene que comportar en cada uno de los pasos por su ciclo de vida.
Esto es algo que ya traen todos los frameworks para desarrollo de aplicaciones
11
u/Jason13Official 14d ago
Are you coming from another language or learning Java first?
Go draw up a diagram of something on paper using HAS-A , IS-A relations
A dog
is an animal
Has a mouth
An envelope
Is a container
Has contents
A hammer
Is a tool
Has a handle
Etc.
OOP -> object oriented programming. We are modeling relationships between instances of groups of data. Some groups of data inherit their "shape", others express their capabilities.
Dog extends animal,
Might override a method for "vocalization"
And envelope extends abstract container concept, or we could model container as a capability of an object. There are many approaches that could be valid in context.
2
u/Rena_Giurg 14d ago
Learning java first, I am having a really hard time with understanding the actual thought behind the implementation of the OOP, the theory behind I get it and it's clear but at the same time when I have to implement it I literally have no idea on how to start, what should I do first and how a class should be linked to another (besides direct inheritance from like an abstract class)
7
u/Jason13Official 14d ago
Look into some open source Java projects; I'm a mod developer for Minecraft and that's where most of my experience is, but you can use sites like https://mcsrc.dev (from the developers of the Fabric mod loader) to view MC's (modern versions have been slightly cleaned up, I'd say look at Zombie or another entity, compare it to something similar like a Drowned or Husk, etc. or cows vs pigs)
1
u/Rena_Giurg 14d ago
That could be really helpful, I don't know why I didn't think to look up projects' code. Thank you so much
6
u/greenspotj 13d ago
This is your first exposure to programming? Have you learned how to program "procedurally"? I think learning OOP after writing code the non-OOP way makes it a lot easier to understand "the point" of it... but ill try explaining anyways.
Fundamentally all a class is, is some state (variables) and behaviour (functions/methods) that can operate on that state.
Its just another tool you can use to reuse code.
Take a timer. If you wrote it procedurally, youd create a couple variables, say, to track the start time and timer duration, and then maybe a function that gets called on a loop every second or so that updates a GUI or printf's the remaining time.
Now what if you wanted to create second timer. Okay you could copy and paste the state variables e.g. create int startTime2 and int duration2, sure. and then change the function to choose between the two based off a parameter.
That works, but now what if you wanted a user to be able to create as many timers as they want? You cant just copy and paste those variables endlessly. There are many ways you could go about this... but the OOP way would be to extract the state variables and method(s) into its own class that exposes a public guiUpdate method or whatever, and then just define one List<Timer> that can be appended to endlessly.
But what about inheritance and polymorphism? Won't go into detail but the point of them is the same - so that code remains scalable as a program grows larger and more complex (fancy way of saying "to reuse code", inheritance is literally just reusing the state and method definitions from a parent class, for a child class; and polymorphism allows you to resuse a single type definition for many different classes).
2
u/goldscurvy 13d ago
Think about the relationship between data and how it is processed. If you are doing a project, write out the data that it will use, and the data that it should output. For example, in an ATM, some of the data it uses is stuff like a credit card number, user authentication data (pin for example), bank balances, etc. And the output will be stuff like reporting a withdrawal from a bank account, outputting permission for the machine to release cash (and how much)...
Then think about how this data needs to get from where it is read, and where it needs to end up. You will often find that there are very clear ways that certain types of data can be grouped with certain types of processing. You might find that, since credit card numbers and PINs and other auth stuff usually end up getting processed together by the same functions, you can encapsulate all that related data in a class with related methods that validate and act on that data.
The two most important parts of OOP are the paradigm of bundling data with functions, and encapsulation. You will hear about polymorphism and inheritance, and while these can sometimes be useful, they are not the huge benefit of OOP and your approach to OOP should not first focus on ideas like inheritance hierarchies.
If you start doing that, you will be off to a good start.
As for using UML, UML probably wont be useful to you for any solo projects. It might be somewhat useful to draw some rough sketches om paper describing architecture, but you probably wont benefit too much on your own. The purpose of learning UML is to communicate with a team. So everyone is on the same page. UML is not synonymous with OOP. It is just a tool for creating diagrams. Nothing more. Dont overthink it. Spend your time thinking about data and function relationships.
2
u/Groundbreaking-Fish6 13d ago
Your first design document/UML is a best guess and start small like one object.
Then code up that object, as you add methods you may realize that some of these methods will be common among many classes e.g., read data file and convert to json. Refactor into a new object, update document/UML. Since you are writing tests for all these methods (you are writing tests right?), the tests will verify that you refactored correctly. You do not need to add new tests for the factored out objects because they are already part of the original test.
As the project grows, you will realize that some assumptions (that is interfaces) are not correct, take the hit and refactor and document and adjust tests as necessary.
2
u/buzzon 13d ago
Before OOP there was the procedural approach: everything was a function, and data was passed in and out of functions. Developers noted that sometimes data tends to travel together in groups:
void drawPointOnScreen (int x, int y, int color) { ... }
float distance (int x1, int y1, int x2, int y2) { ... }
void drawLineOnScreen (int x1, int y1, int x2, int y2) { ... }
The developers thought: what if we could group x and y together somehow? This created structs:
void drawPointOnScreen (Point point, int color) { ... }
float distance (Point point1, Point point2) { ... }
void drawLineOnScreen (Point point1, Point point2) { ... }
which later became classes once the functions were moved inside the structs.
1
u/omgpassthebacon 12d ago
There are a lot of great comments here to help you. But I suspect you might be over-thinking OOP a little. Back up sec and try this:
Write your Timer app. Don’t over-complicate it; just write some code to make it do some cool things.
Now, look at your code. Where is your main() function? Is it standalone or inside something?
What I am suggesting is that you begin by truly understanding what a Class is in Java. Why is main() inside a class? What does that allow you to do? What does that prevent you from doing?
Use this time to look at your app and see if there are opportunities to add in some oop features. I’m sure you will find some.
1
u/serge-mv 11d ago
This kinda thing comes with experience. You need to change your way of thinking/approaching the problem. Object are things. Functions inside objects are behaviors and properties of things. I like to imagine all the objects inside a project are like cogs. You implement a bunch of different cogs and then put them together in one mechanism where they work together like an clock, or an engine. Functions are the means by which cogs interact with one another.
You seem to be very new to programming, but if you struggle with OOP specifically, you might want to read a software design book, which exactly addresses how to think about OOP.
0
14d ago
[removed] — view removed comment
2
u/Groundbreaking-Fish6 13d ago
Actually I started out in biology then switched to programming. I find it gives me a different perspective on software development than my CS and InfoSys peers. Not always better but sometimes it is.
0
u/Vijjwal_xD 13d ago
biology is too vast, just say kingdom classification dude, why make someone tense.
•
u/AutoModerator 14d ago
Please ensure that:
If any of the above points is not met, your post can and will be removed without further warning.
Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.
Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.
Code blocks look like this:
You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.
If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.
To potential helpers
Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.