Um momento
0x50Lesson 6 of 6

Organize behavior with methods and objects

Define a reusable method and model data with a simple class.

14 min 4-question quiz 1 code exercise
By the end of this lesson you can
  • Call a method on an object and use its returned value.

A method gives a name to a reusable operation. A method can accept parameters and return a value. A class describes a kind of object with fields and methods; an object is a particular instance created from that class. This lets related state and behavior live together.

Main.java
1class Rectangle {
2    int width;
3    int height;
4
5    int area() {
6        return width * height;
7    }
8}
Output
area() returns width × height

A constructor can initialize fields when a new object is created. this.width refers to the current object’s width field. Java’s standard library also provides classes for common data structures and tasks; choose a simple class design that makes each responsibility clear.

Key takeaways

  • Call a method on an object and use its returned value.

  • Java checks types as it compiles your source.

  • Use compiler messages as clues about what needs fixing.

Lesson quiz

4 questions · pass with 3 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write Java

Write Java in the editor and run it against sample input with a remote compiler. Your code is sent to Compiler Explorer to compile and run.

Exercise 1

Calculate a rectangle’s area

+25 XP

Complete the Rectangle class with a constructor and area() method. Read width and height, create a Rectangle, and print its area.

  • Three by four
  • Five by two
Main.java
Loading editor…

Java is compiled and run by Compiler Explorer (godbolt.org), a free public service. Your source code and test input are sent to that service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…

Gostou da aula? 😆👍
Apoie nosso trabalho com uma doação: