Sample Classes in Python vs Java
00:00 Welcome to lesson one of Object-Oriented Programming in Python versus Java. In this lesson, we will look at a simple class written in both Java and in Python.
00:12
The Java class is going to be in a file called Car.java
and it will have the typical organization of a Java class with its fields, constructor, and some get methods.
00:26
So, here we have a class Car
. We define three fields—the color, model, and its year. We have a constructor assigning values to each of those fields and some typical get methods to obtain the values of those fields.
00:47 Python classes, you’ll notice, are going to be a lot smaller. There’s no requirement that the filename match the class name nor that there be only one class in a particular Python file.
01:00
All of our attributes are defined in what’s called an .__init__()
method.
01:07
So, comparing our Java class to our Python class, we define class Car
and then we have our .__init__()
method, which is similar to a constructor. Behind the scenes they’re not really the same, but if you want to view writing a Java constructor, it would go into this dunder method—a method that begins and ends with two underscores (__
) is referred to as a dunder method—called .__init__()
.
01:39
We don’t have to declare the fields ahead of time. The fields are defined when we assign them a value. So when we say self.color = color
, that defines the field .color
.
01:53
Similarly, this statement defines the field .model
and this statement defines the field .year
. In the remainder of this course, we will dig deeper into these differences—why it’s so much smaller, why we’re missing things like public
and private
—but the first thing we’re going to be taking a look at will be the declaration and initialization of fields.
Become a Member to join the conversation.