This program is implemented by Naman Dhiman from NIT Uttrakhand
import java.util.Scanner;
public class Book {
// non static data members
int id;
String topic;
String author;
float price;
String publisher;
// no argument constructor of Book
public Book()
{
// initializing the data members
id = 101;
topic = "Let Us C";
author = "Kanethkar";
price = 350.2f;
publisher = "Macmillan";
}
// parameterized constructor of Book
public Book(int id, String topic, String author, float price, String publisher) {
// initializing the data members
// this.id means non static variable while id is a local variable
this.id = id;
this.topic = topic;
this.author = author;
this.price = price;
this.publisher = publisher;
}
// non static method to show data of Book
void info()
{
System.out.println("ID = "+id);
System.out.println("Topic = "+topic);
System.out.println("Author = "+author);
System.out.println("Price = "+price);
System.out.println("Publisher = "+publisher);
}
public static void main(String[] args) {
// create object of Book using no argument constructor
Book b1 = new Book();
// show info of Book
b1.info();
// create object of Book using parameterized constructor
Book b2 = new Book(102,"Concepts in Java","Herbert Schildt",800.5f,"PHI");
// show info of Book
b2.info();
// create object of Book using parameterized constructor
Book b3 = new Book(103,"C","E.Balaguruswamy",400.75f,"Hachette");
// show info of Book
b3.info();
// object of Scanner to take input from keyboard
Scanner sc = new Scanner(System.in);
// take some inputs
System.out.println("Enter Book id");
int id = sc.nextInt();
System.out.println("Enter book topic");
String topic = sc.next();
System.out.println("Enter Author's Name");
String author = sc.next();
System.out.println("Enter Price");
float price = sc.nextFloat();
System.out.println("Enter Publisher's Name");
String publisher = sc.next();
// create object of Book using parameterized constructor
// here we are passing variable names as arguments
Book b4 = new Book(id,topic,author,price,publisher);
// show info of Book
b4.info();
}
}
No comments:
Post a Comment