- Hands-On Design Patterns with Java
- Dr. Edward Lavieri
- 257字
- 2021-06-24 14:57:58
Sample OOP class
Let's develop our Bicycle class further by adding attributes and a behavior. The attributes will be the number of gears, how much the bicycle cost, the weight, and the color. The behavior will be the ability to output the attribute values. Here is the source code:
public class Bicycle extends TwoWheeled {
// instance variable declarations
private int gears = 0;
private double cost = 0.0;
private double weight = 0.0;
private String color = "";
// method to output Bicycle's information
public void outputData() {
System.out.println("\nBicycle Details:");
System.out.println("Gears : " + this.gears);
System.out.println("Cost : " + this.cost);
System.out.println("Weight : " + this.weight + " lbs");
System.out.println("Color : " + this.color);
}
Here is the code for Setters:
public void setGears(int nbr) {
this.gears = nbr;
}
public void setCost(double amt) {
this.cost = amt;
}
public void setWeight(double lbs) {
this.weight = lbs;
}
public void setColor(String theColor) {
this.color = theColor;
}
}
We will take a look at all components of the Bicycle class in subsequent sections. For now, focus on the public void outputData() method. We will use our Driver class to evoke that method. Here is the updated Driver class:
public class Driver {
public static void main(String[] args) {
Bicycle myBike = new Bicycle();
myBike.setGears(24);
myBike.setCost(319.99);
myBike.setWeight(13.5);
myBike.setColor("Purple");
myBike.outputData();
}
}
In the preceding Driver class, we create an instance of Bicycle called myBike, assign values to its attributes, and then make a call to the outputData() method. Here are the output results:

Driver class output
推薦閱讀
- 數據存儲架構與技術
- 算法與數據中臺:基于Google、Facebook與微博實踐
- Creating Dynamic UIs with Android Fragments(Second Edition)
- Sybase數據庫在UNIX、Windows上的實施和管理
- 數據庫程序員面試筆試真題庫
- Spark大數據分析實戰
- Mastering LOB Development for Silverlight 5:A Case Study in Action
- Visual Studio 2013 and .NET 4.5 Expert Cookbook
- Oracle 11g+ASP.NET數據庫系統開發案例教程
- The Natural Language Processing Workshop
- 數據庫原理與設計實驗教程(MySQL版)
- 離線和實時大數據開發實戰
- 大數據技術體系詳解:原理、架構與實踐
- 碼上行動:利用Python與ChatGPT高效搞定Excel數據分析
- 數據產品經理寶典:大數據時代如何創造卓越產品