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.
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.
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.
All of our attributes are defined in what’s called an
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
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
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
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.