Beginner at Java (object orientated programming) Watch

Nihilisticb*tch
Badges: 22
Rep:
?
#1
Report Thread starter 1 year ago
#1
I have learnt python for a few years at school and had no problem with it although I found that it isn't as versatile or considered as useful as other languages. I decided to start learning java this summer but I have had problems with the object orientated side of it. I never had need for classes and objects when I used python but perhaps this is because I didn't know about them. I understand the concept of classes and objects (classes are the type of thinh, objects are an instance of the type of thing) but I can't really understand how to use it in a practical sense or why it is necessary. I also don't understand a lot of the syntax of how to use classes. If anyone could help me with this then that would be great.
0
reply
62636466696e7669
Badges: 5
Rep:
?
#2
Report 1 year ago
#2
First off, I'd disagree with you on the versatility of python as there are hundreds of libraries and modules for a range of uses, eg: Django and Flask as web frameworks or Numpy and MatPlotLib for science and data representation. However I guess it is mainly a matter of opinion and depends on what you want to do with the language. Answering your question, I also struggled with classes and grew tired of the useless "foo/bar" examples used in most tutorials, so decided to make a class that I could actually implement into my code at the time when I was learning. This happened to be a vector class for a simple game which really helped my mind "click" with the relationships between classes and instances and attributes.

take this simplified class:
class Vector:
....def __init__(self,vector):
........self.v = vector

....def magnitude(self):
........total = 0
........for x in self.v:
............total += x**2
........return sqrt(total)

For example a vector object could be created by passing a list into the Vector class: named_vector = Vector( [3,4] )
The special method __init__() in the Vector class is then called, where a variable specific only to the named_vector object is created: self.v, which is the parameter passed during instantiation ( [3,4] ).

This instance variable can then referred to outside the class later on in the code by calling named_vector.v
Now this is where it gets kind of confusing, the magnitude class method uses the Pythagorean theorem to calculate the magnitude of a specific object. It does this by using self.v, which is unique to the instance of the class that it is called by. So for example, if named_vector.magnitude() were to be called, self.v within the method is equivalent to named_vector.v so sqrt(3**2+4**2) or 5 would be returned.

However, if we instantiated another object: named_vector_2 = Vector( [1,1] ) , and called named_vector_2.magnitude() would return sqrt(2), as the values of self.v ( or named_vector_2.v ) are different even thought the same method is being called.

Note that, in Python all methods used in a class that contain self.<variable name> MUST have self as a parameter, however this is only specific to Python and not needed in any other language that I know of.

Hopefully this cleared up any basics, and if you have any other questions I'd be happy to answer them for you. I've included the vector module I used to learn classes that contains a more detailed version of the simplified example used here.
Some pointers on what to research: Decorators, Special Methods, Class/Instance Variables, Inheritance
0
reply
Nihilisticb*tch
Badges: 22
Rep:
?
#3
Report Thread starter 1 year ago
#3
(Original post by 62636466696e7669)
First off, I'd disagree with you on the versatility of python as there are hundreds of libraries and modules for a range of uses, eg: Django and Flask as web frameworks or Numpy and MatPlotLib for science and data representation. However I guess it is mainly a matter of opinion and depends on what you want to do with the language. Answering your question, I also struggled with classes and grew tired of the useless "foo/bar" examples used in most tutorials, so decided to make a class that I could actually implement into my code at the time when I was learning. This happened to be a vector class for a simple game which really helped my mind "click" with the relationships between classes and instances and attributes.

take this simplified class:
class Vector:
....def __init__(self,vector):
........self.v = vector

def magnitude(self):
....total = 0
....for x in self.v:
........total += x**2
....return sqrt(total)

For example a vector object could be created by passing a list into the Vector class: named_vector = Vector( [3,4] )
The special method __init__() in the Vector class is then called, where a variable specific only to the named_vector object is created: self.v, which is the parameter passed during instantiation ( [3,4] ).

This instance variable can then referred to outside the class later on in the code by calling named_vector.v
Now this is where it gets kind of confusing, the magnitude class method uses the Pythagorean theorem to calculate the magnitude of a specific object. It does this by using self.v, which is unique to the instance of the class that it is called by. So for example, if named_vector.magnitude() were to be called, self.v within the method is equivalent to named_vector.v so sqrt(3**2+4**2) or 5 would be returned.

However, if we instantiated another object: named_vector_2 = Vector( [1,1] ) , and called named_vector_2.magnitude() would return sqrt(2), as the values of self.v ( or named_vector_2.v ) are different even thought the same method is being called.

Note that, in Python all methods used in a class that contain self.<variable name> MUST have self as a parameter, however this is only specific to Python and not needed in any other language that I know of.

Hopefully this cleared up any basics, and if you have any other questions I'd be happy to answer them for you. I've included the vector module I used to learn classes that contains a more detailed version of the simplified example used here.
Some pointers on what to research: Decorators, Special Methods, Class/Instance Variables, Inheritance
Thank you this was a very helpful reply.
0
reply
winterscoming
Badges: 19
Rep:
?
#4
Report 1 year ago
#4
(Original post by Nihilisticb*tch)
I have learnt python for a few years at school and had no problem with it although I found that it isn't as versatile or considered as useful as other languages. I decided to start learning java this summer but I have had problems with the object orientated side of it. I never had need for classes and objects when I used python but perhaps this is because I didn't know about them. I understand the concept of classes and objects (classes are the type of thinh, objects are an instance of the type of thing) but I can't really understand how to use it in a practical sense or why it is necessary. I also don't understand a lot of the syntax of how to use classes. If anyone could help me with this then that would be great.
The word "necessary" is far too strong and absolutist. Object orientation is not at all necessary for the computer or the compiler/interpreter and it doesn't magically open up any new possibilities compared to simple procedural code. A better term would be "strongly preferred"; that is to say, anything you can do with a programming language using objects and classes can also be done without objects and classes, albeit usually in a less-organised and less-structured manner.

Computers themselves have no concept of object-oriented programming; it's entirely a human construct whose sole purpose is to make life easier for humans who are trying to reason over code. Object-orientation exists because humans working with programs which contain a lot of code tend to benefit from having ways to structure code in a way which makes logical sense to them, and hopefully to other humans.

Object-oriented programming actually isn't even all about programming, it's about thinking. At its very core, "OO" is simply about the way that you create a logical grouping of related code in your program. That means identifying some part of your program where part of the code relates to some particular bit of functionality or maybe a functional user requirement, and grouping all of that code together with a name which helps provide extra meaning and context (i.e. code which has a semantic relationship or some kind of affinity with other logically related code) .

For example, consider some mathematical code working with angles. Object-orientation means that you get to think about the intent of the code -- this means writing code in a way which gives other human readers an easy time understanding exactly what you intended your code to achieve.
Code:
aircraft = Helicopter()
bearing = Angle(Degrees(5))
aircraft.ChangeDirection(bearing)
What's interesting about this code? Well, the fact that it's clearly doing some maths, except you can't actually see what that maths is, yet pretty much any human who looks at that code would be able to look at it and say "Oh it's telling a helicopter to change its direction on a bearing of 5 degrees".

How is it doing that? What maths is involved? The best part about it is that you don't know and you don't care. Object-oriented programming is about selective ignorance (the 'proper' term for that is 'Encapsulation').

aircraft is an object with a method called ChangeDirection - the aircraft object and the ChangeDirection method care about the maths, but the part of the program which is telling the aircraft to change direction really doesn't care how it works.

The other analogy to Object-oriented programming is like driving a car. Last time I checked, most people who drive a car have no idea how a car changes gear or accelerates forward -- that doesn't matter because the driver of the car only needs to understand the car's interface; i.e. the steering wheel, pedals and gears. If you as the car's user understand the Car's methods such as "Turn the steering wheel" or "Push the brake" or "Change gear" then your 'Car' object will know what to do, and the mechanics/electronics sitting inside the chassis will cause the car to speed up, slow down, turn, stop, etc.


Is this really necessary? could the same code have been written without classes? Well, yes, and the computer couldn't care less if you do. But what about the driving analogy - should someone learning to drive a car be forced to understand how to build the engine and how all of the components work together before they're able to sit in the seat and drive to the shop? Drivers of a car have selective ignorance because they don't know or care how the car works and they don't need to. In general, things are better that way because driving is easy and accessible to humans. People who use classes in their code (assuming they put careful thought into those classes) end up writing code which is much more accessible and easy to reason over by humans.

That's really the rationale behind object-oriented programming. It's a fairly simple idea but it has huge implications for the way you write code. Particularly when you start writing bigger, more complex programs - once you find yourself writing lots of functions which have a very high cognitive overhead for someone reading them, it's time to consider how to split those functions down and to think about identifying the logically separate responsibilities in your code, then using classes to create logically separate components which could make the code easier to read, and easier to reason over.
0
reply
Nihilisticb*tch
Badges: 22
Rep:
?
#5
Report Thread starter 1 year ago
#5
(Original post by winterscoming)
The word "necessary" is far too strong and absolutist. Object orientation is not at all necessary for the computer or the compiler/interpreter and it doesn't magically open up any new possibilities compared to simple procedural code. A better term would be "strongly preferred"; that is to say, anything you can do with a programming language using objects and classes can also be done without objects and classes, albeit usually in a less-organised and less-structured manner.

Computers themselves have no concept of object-oriented programming; it's entirely a human construct whose sole purpose is to make life easier for humans who are trying to reason over code. Object-orientation exists because humans working with programs which contain a lot of code tend to benefit from having ways to structure code in a way which makes logical sense to them, and hopefully to other humans.

Object-oriented programming actually isn't even all about programming, it's about thinking. At its very core, "OO" is simply about the way that you create a logical grouping of related code in your program. That means identifying some part of your program where part of the code relates to some particular bit of functionality or maybe a functional user requirement, and grouping all of that code together with a name which helps provide extra meaning and context (i.e. code which has a semantic relationship or some kind of affinity with other logically related code) .

For example, consider some mathematical code working with angles. Object-orientation means that you get to think about the intent of the code -- this means writing code in a way which gives other human readers an easy time understanding exactly what you intended your code to achieve.
Code:
aircraft = Helicopter()
bearing = Angle(Degrees(5))
aircraft.ChangeDirection(bearing)
What's interesting about this code? Well, the fact that it's clearly doing some maths, except you can't actually see what that maths is, yet pretty much any human who looks at that code would be able to look at it and say "Oh it's telling a helicopter to change its direction on a bearing of 5 degrees".

How is it doing that? What maths is involved? The best part about it is that you don't know and you don't care. Object-oriented programming is about selective ignorance (the 'proper' term for that is 'Encapsulation').

aircraft is an object with a method called ChangeDirection - the aircraft object and the ChangeDirection method care about the maths, but the part of the program which is telling the aircraft to change direction really doesn't care how it works.

The other analogy to Object-oriented programming is like driving a car. Last time I checked, most people who drive a car have no idea how a car changes gear or accelerates forward -- that doesn't matter because the driver of the car only needs to understand the car's interface; i.e. the steering wheel, pedals and gears. If you as the car's user understand the Car's methods such as "Turn the steering wheel" or "Push the brake" or "Change gear" then your 'Car' object will know what to do, and the mechanics/electronics sitting inside the chassis will cause the car to speed up, slow down, turn, stop, etc.


Is this really necessary? could the same code have been written without classes? Well, yes, and the computer couldn't care less if you do. But what about the driving analogy - should someone learning to drive a car be forced to understand how to build the engine and how all of the components work together before they're able to sit in the seat and drive to the shop? Drivers of a car have selective ignorance because they don't know or care how the car works and they don't need to. In general, things are better that way because driving is easy and accessible to humans. People who use classes in their code (assuming they put careful thought into those classes) end up writing code which is much more accessible and easy to reason over by humans.

That's really the rationale behind object-oriented programming. It's a fairly simple idea but it has huge implications for the way you write code. Particularly when you start writing bigger, more complex programs - once you find yourself writing lots of functions which have a very high cognitive overhead for someone reading them, it's time to consider how to split those functions down and to think about identifying the logically separate responsibilities in your code, then using classes to create logically separate components which could make the code easier to read, and easier to reason over.
Thank you, this has helped me to understand object orientated programming. I think part of my misunderstanding was in that I wrongly believed that there were some situations where it was necessary but now I understand that it just makes things easier. I have never made a massive program so I guess I wouldn't have encountered the issues that object orientated programming solves.
1
reply
winterscoming
Badges: 19
Rep:
?
#6
Report 1 year ago
#6
(Original post by Nihilisticb*tch)
Thank you, this has helped me to understand object orientated programming. I think part of my misunderstanding was in that I wrongly believed that there were some situations where it was necessary but now I understand that it just makes things easier. I have never made a massive program so I guess I wouldn't have encountered the issues that object orientated programming solves.
Overall it doesn't make much of a difference when your program is only a few hundred lines of code - the problem with writing code like that is that once code starts growing, it can end up reaching a point where it's easier to create a new project and write all of the code from scratch than trying to chop the code into pieces and rearrange it into classes. "OO" is one of those things which you need to think about from the start otherwise rearranging it becomes almost impossible later on.

Another thing to consider - OO code is all around you even if you hadn't noticed it yet. While you're there writing code without classes, the Python libraries make extensive use of classes

For example, if you've ever used files in Python, you've probably seen code which looks like this:
Code:
with open('filename', 'r') as f:
    line = f.readline()
It turns out that Python has a class called File. When you use the open() function (which isn't part of the File class), it returns an object based on Python's File class. The File class has a method called readline() which reads a line from that file without you needing to know how file input works under the hood. So you've unwittingly been using object oriented code for a long time already, you just probably haven't written much object oriented code yourself.

There's also Python's built-in string class too which I expect you've already been using with methods ilke format() and replace().

It's useful to get into the habit of 'thinking' about objects even if their benefit isn't obvious. Even if you write a class which only has a couple of methods, each of which are only a couple of lines long, that's a good way to get started. There's usually no such thing as a class being "too small" as long as that class represents something useful, like a string, or a file, or a network connection, or a database, or a GUI button, etc..
0
reply
Nihilisticb*tch
Badges: 22
Rep:
?
#7
Report Thread starter 1 year ago
#7
(Original post by winterscoming)
Overall it doesn't make much of a difference when your program is only a few hundred lines of code - the problem with writing code like that is that once code starts growing, it can end up reaching a point where it's easier to create a new project and write all of the code from scratch than trying to chop the code into pieces and rearrange it into classes. "OO" is one of those things which you need to think about from the start otherwise rearranging it becomes almost impossible later on.

Another thing to consider - OO code is all around you even if you hadn't noticed it yet. While you're there writing code without classes, the Python libraries make extensive use of classes

For example, if you've ever used files in Python, you've probably seen code which looks like this:
Code:
with open('filename', 'r') as f:
    line = f.readline()
It turns out that Python has a class called File. When you use the open() function (which isn't part of the File class), it returns an object based on Python's File class. The File class has a method called readline() which reads a line from that file without you needing to know how file input works under the hood. So you've unwittingly been using object oriented code for a long time already, you just probably haven't written much object oriented code yourself.

There's also Python's built-in string class too which I expect you've already been using with methods ilke format() and replace().

It's useful to get into the habit of 'thinking' about objects even if their benefit isn't obvious. Even if you write a class which only has a couple of methods, each of which are only a couple of lines long, that's a good way to get started. There's usually no such thing as a class being "too small" as long as that class represents something useful, like a string, or a file, or a network connection, or a database, or a GUI button, etc..
Yes I realise that now. I think that although I am not advanced enough to create huge programs, I should start getting into the habit of using classes and objects so that the skills are there when I do become that advanced. You have been helpful in clearing up my issue thank you
0
reply
X

Quick Reply

Attached files
Write a reply...
Reply
new posts
Back
to top
Latest
My Feed

See more of what you like on
The Student Room

You can personalise what you see on TSR. Tell us a little about yourself to get started.

Personalise

University open days

  • University of Surrey
    Postgraduate Open Afternoon Postgraduate
    Wed, 23 Oct '19
  • University of Bristol
    Undergraduate Open Afternoon Undergraduate
    Wed, 23 Oct '19
  • University of Exeter
    Undergraduate Open Day - Penryn Campus Undergraduate
    Wed, 23 Oct '19

Would you turn to a teacher if you were being bullied?

Yes (57)
23.75%
No (183)
76.25%

Watched Threads

View All