Java: Objects as arguments to methods

Java allows us to pass objects as arguments to methods.

Like passing an array, passing an object is actually passing the reference of the object.

This example depicts BookStore application. The showBook() method receives a book object as an argument and displays isbn, author and title of the book.

package javaapplication28;

public class BookClass {

    static class Book {

        int isbn;
        String author;
        String title;

        public void init(int isbn, String author, String title) {
            this.isbn = isbn; // this.isbn refers to instance variable,
            // isbn refers to local variable
            this.author = author;
            this.title = title;
        }
    }
    
    public static class BookStore {

        public void showBook(Book b) {
            System.out.println("ISBN: " + b.isbn + "\nTitle: " + b.title + "\nAuthor: " + b.author);
            System.out.println();
        }
    }

    static public class LibraryBook extends Book {

        int nCopies = 10; // number of copies of the book

        public void show() {
            System.out.println("isbn = " + isbn + "\nauthor = " + author + "\ntitle = " + title + "\ncopies = " + nCopies);
        }
    }
   
    public static void main(String[] args) {

        Book b = new Book();
        b.init(1234, "Peter", "Java");
        BookStore bs = new BookStore();
        bs.showBook(b);

        LibraryBook lb = new LibraryBook();
        lb.init(4321, "Jeniffer", "Data Structures");
        lb.show();

    }
}

inheritance

Series Navigation<< Java: Inheriting a class with members
Java: Basic concept of inheritance >>