DEV Community

Cover image for "Key Syntax Differences in Object-Oriented Programming: Python vs. Java”
Mahia  Momo
Mahia Momo

Posted on

2

"Key Syntax Differences in Object-Oriented Programming: Python vs. Java”

class & object

python code:

#Student is the class
class Student:
    name = "Momo";

#here s1 is the object of Student class
s1 = Student()   
print(s1.name)

Enter fullscreen mode Exit fullscreen mode

constructor

python code

class Student:

    def __init__(self,fullname):  #constructor 
        self.name = fullname

s1 = Student("Momo")
print(s1.name)

Enter fullscreen mode Exit fullscreen mode

class & object in java

java code:

// Student is the class
class Student {
    String name = "Momo";
}

// Main class to test the Student class
public class Main {
    public static void main(String[] args) {
        // s1 is the object of the Student class
        Student s1 = new Student();
        System.out.println(s1.name);
    }
}

Enter fullscreen mode Exit fullscreen mode

constructor in java

java code:

// Student class
class Student {
    String name; // Instance variable

    // Constructor
    public Student(String fullname) {
        this.name = fullname;
    }
}

// Main class to test the Student class
public class Main1 {
    public static void main(String[] args) {
        // Create an object of the Student class
        Student s1 = new Student("Momo");
        // Print the name
        System.out.println(s1.name);
    }
}

Enter fullscreen mode Exit fullscreen mode

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (2)

Collapse
 
khmarbaise profile image
Karl Heinz Marbaise

Why not using a record; is easier:

record Student(String name) {}

public class Main1 {
    public static void main(String[] args) {
        var s1 = new Student("Momo");
        System.out.println(s1.fname());
    }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mahiamomo profile image
Mahia Momo

ok i'll remind it thank you so much for the suggestion

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay