7. Method

7.2. Practical Examples

Below are two programs—one in Java and one in Python—demonstrating class, object, attribute, and method. They use basic data types (int, double/float, boolean, String/str, char), variables, expressions, assignment statements, and operators (arithmetic, relational, string concatenation), keeping the structure similar to your previous examples.

Java Example

class Person {

// Attributes String name;

int age; double height;

// In feet char initial;

 boolean isAdult;

// Constructor to initialize attributes

Person(String name, int age, double height, char initial) {

    this.name = name; // Assignment statement

    this.age = age;

    this.height = height;

    this.initial = initial;

    this.isAdult = age >= 18; // Expression with relational operator

}

 

// Method to display greeting

void sayHello() {

    String greeting = "Hello, " + name; // Expression with string concatenation

    System.out.println(greeting);

}

 

// Method to calculate height in meters