Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Java is an OO language, so there's no getting away from classes when you use Java, unlike in Python, where OO features can be avoided. Python programmers, mostly prefer not to use Python's OO features.

Let's take a look at some code, starting with Python.

A Python Class

As is the case with Python in general, the Python OO paradigm is pretty concise, as the simple class in the following listing. The Student class has three data members: name, age, and major subject.

An Equivalent Java Class

Not to be outdone by our Python coding effort, the second Listing shows an equivalent Java class.

Code Block
languagepy
titleA Python class
 class Student:
    def __init__(self, name, age, major):
        self.name = name
        self.age = age
        self.major = major

    def is_old(self):
        return self.age > 100

The __init__() method is the closest thing Python has to a constructor. Notice the use of self.nameto initialize the state of the instance. Also included is the simple method is_old() to determine (in a slightly "ageist" manner) whether the underlying student is young or old (with "old" being over 100 years).

The code in listing illustrates one of the great merits of OO programming: Code and data reside in close proximity to each other. Data is of course the repository of state, so the use of OO brings code, data, and state together in a manner useful to programmers. Clearly, you can do all of this without OO code, but OO makes it a matter of rather beautiful simplicity.

Code Block
languagejava
titleA Java student class
public class Student {
	String name; 
	int age; 
	String major; 
	public Student() { 
		// TODO Auto-generated constructor stub 
	} 	
	public Student(String name, int age, String major) { 
		this.name = name; 	
		this.age = age; 
		this.major = major; 
	} 
}
The Java code in this listing is very similar to the Python code in previous. Notice that the use of OO can produce quite readable code in either language. Python listing is not likely to baffle a Java programmer, even without a background in Python. Likewise, a Python programmer well versed in the Python OO features would easily understand the Java code in the second listing.