In this project, we move beyond simple object creation to defining object behavior. We model a Book as a digital entity that not only stores data (title and pages) but also possesses the ability to describe itself through a dedicated method. This encapsulates both the state and the functionality within a single class structure.
- Class Structure: Defined a
Bookclass withString titleandint pages. - Method Implementation: Created a
printInfo()method to display book details. - Object Instantiation: Created an instance named
myBook(or similar) in themainmethod. - Data Assignment: Assigned "Java for Beginners" and 350 pages to the instance.
- Behavior Execution: Successfully called the
printInfo()method.
- Java 8+ (Core OOP: Fields and Methods)
Methods like printInfo() allow objects to perform actions using their internal data. When printInfo() is called, it accesses the specific title and pages associated with that particular instance of the Book.
Title: Java for Beginners, pages: 350
Project Structure:
src/com/yurii/pavlenko/
├── Book.java
└── Solution.java
Code
package com.yurii.pavlenko;
public class Solution {
public static void main(String[] args) {
Book myBook = new Book();
myBook.title = "Java for Beginners";
myBook.pages = 350;
myBook.printInfo();
}
}package com.yurii.pavlenko;
public class Book {
public String title;
public int pages;
public void printInfo() {
System.out.println("Title: " + title + ", pages: " + pages);
}
}This project is licensed under the MIT License.
Copyright (c) 2026 Yurii Pavlenko
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files...
License: MIT