SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Michael T. Goodrich, Roberto Tamassia, Michael H. Goldwasser
Chapter:
Java Primer
Exercise:
Exercises
Question:10 | ISBN:9781118771334 | Edition: 6

Question

Write a Java class, Flower, that has three instance variables of type String, int, and float, which respectively represent the name of the flower, its number of petals, and price. Your class must include a constructor method that initializes each variable to an appropriate value, and your class should include methods for setting the value of each type, and getting the value of each type.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

package java_problems_datastructures;

public class Flower {

	String flower;
	int petals;
	float price; // in rupees

	public Flower(String flower, int petals, float price) {

		this.flower = flower;
		this.petals = petals;
		this.price = price;
	}

	// below are getters and setters

	public String getFlower() {
		return flower;
	}

	public void setFlower(String flower) {
		this.flower = flower;
	}

	public int getPetals() {
		return petals;
	}

	public void setPetals(int petals) {
		this.petals = petals;
	}

	public float getPrice() {
		return price;
	}

	public void setPrice(float price) {
		this.price = price;
	}

	public static void main(String[] args) {
		/*
		 * you can intialize the values through constructor method or through getter and
		 * setter methods defined in class
		 */

		Flower flower = new Flower("astor flower", 12, 6.99f);

		// print the values using getter methods

		System.out.println("the flower name, petals count and price respectively is: " + flower.getFlower() + ", "
				+ flower.getPetals() + ", " + flower.getPrice() + ", ");

	}

}

 

0 0

Discussions

Post the discussion to improve the above solution.