当前位置:网站首页>Experiment five categories and objects
Experiment five categories and objects
2022-07-06 13:55:00 【Wen Wen likes Guo Zia】
Experiment five Classes and objects
The experiment purpose
1. master Java Definition of language category 、 Object creation 、 Object reference method .
2. Have a preliminary understanding of object-oriented design methods
Experimental hours 6 Class hours
Experimental content
1. Design a ballpoint pen class BallPen, Yes 1 Attributes boolean penPoint( Whether the nib extends ), Yes 4 A way :
(1) Construction method BallPen (), take penPoint Set as false
(2) Press operation method void knock(), take penPoint Inversion
(3) How to get the nib state boollean getPenPoint()
(4)main Method
Create an object and press the instance object , Display the status of the nib .
package code51;
public class BallPen { // take penPoint Set as false
boolean penPoint;
BallPen() {
penPoint=false;
}
void knock() { // take penPoint Inversion
if(penPoint==false)
{
penPoint=true;
}
else
{
penPoint=false;
}
}
boolean getPenPoint() { // Get the nib status
return penPoint;
}
public static void main(String args[]) {
BallPen a = new BallPen(); // Create objects
a.knock(); // Press the instance object
System.out.println("penPoint="+a.getPenPoint()); // Display the status of the nib
}
}
2. Design a car class Car, Yes 2 Attribute owner owner And oil quantity oil, Yes 7 A way :
(1) Construction method Car(String owner,double oil)
(2) Construction method Car(String owner), Set the oil volume to 0
(3) Refueling operation method void addOil(double oil)
(4) Driving operation method void drive(int distance)
Suppose that every 100 The fuel consumption per kilometer is a constant ( Set up your own ), Update the fuel volume according to the mileage .
(5) How to get owner information String getOwner()
(6) Method of obtaining oil quantity double getOil()
(7)main Method
Create an object and refuel the instance object 、 Driving operation , Show owner 、 Oil quantity .
package code52;
public class Car {
String owner;
double oil;
double x;
int distance;
Car(String owner,double oil) {
this.owner=owner;
this.oil=oil;
}
Car(String owner) { // Set the oil volume to 0
oil=0;
}
void addOil(double oil) { // Refuel
oil+=x;
}
void drive(int distance) { // Update the fuel volume according to the mileage
oil-=(distance/100*10);
}
String getOwner() { // Get owner information
return owner;
}
double getOil() { // Get the oil quantity
return oil;
}
public static void main(String args[]) {
Car a = new Car(" Bowen huang ",100); // Create objects
a.addOil(100); // Refuel the instance object
a.drive(200); // Run the instance object
System.out.println("owner="+a.getOwner()); // Show owner
System.out.println("oil="+a.getOil()); // Display the oil quantity
}
}
3. Write a class to represent coordinate points , Class contains constructor to assign coordinates when creating a new class . Write another tool class about coordinate points .
(1) Write coordinate point class Point.
(2) Write a tool class PointUtil, Contains methods double distance(Point a,Point b) Used to calculate the distance between two coordinate points , And methods double area(Point a,Point b) It is used to calculate the rectangular area where the line between two points is diagonal .
(3) Write the main method to calculate the coordinates (2,10) To coordinates (4,55) Distance between and rectangular area .
package code53;
public class PointUtil {
int x;
int y;
public PointUtil(int x,int y) {
this.x=x;
this.y=y;
}
double distance(PointUtil x1,PointUtil x2)
{
double distance=Math.sqrt((x1.x-x2.x)*(x1.x-x2.x)+(x1.y-x2.y)*(x1.y-x2.y));
return distance; // Find the distance between two coordinate points
}
double area(PointUtil x1,PointUtil x2)
{
double area=(x1.x-x2.x)*(x1.y-x2.y);
if(area<0)
{
area=-area;
}
return area; // Find the area of a rectangle with two diagonal lines
}
}
package code53;
import java.util.Scanner;
public class Point {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println(" Please enter the coordinates of the two points :");
PointUtil x1 = new PointUtil(in.nextInt(),in.nextInt()); // Create objects and point x1 Coordinate assignment
PointUtil x2 = new PointUtil(in.nextInt(),in.nextInt()); // Create objects and point x2 Coordinate assignment
double distance=x1.distance(x1, x2); // Call the method to find the distance between two points
double area=x1.area(x1, x2); // Call method to calculate rectangular area
System.out.println(" The distance between the two coordinate points is :"+distance);
System.out.println(" The area enclosed in a rectangle is :"+area);
}
}
4. To write Java The program simulates a simple calculator . Definition is named Number Class , There are two private integer data members x and y. Yes 7 A way :
(1) Construction method Number(int x,int y)
(2) Addition method int addition(int x,int y)
(3) Subtraction method int subtration(int x,int y)
(4) Multiplication method int multiplication(int x,int y)
(5) Division operation method int division(int x,int y)
Write another test class , Yes Number Class to test .
package code54;
public class Number {
int x,y;
Number(int x,int y) {
this.x = x;
this.y = y;
}
int addition(int x,int y) { // To add
return x+y;
}
int subtration(int x,int y) { // Do subtraction
return x-y;
}
int multiplication(int x,int y) { // Multiply
return x*y;
}
int division(int x,int y) { // Do Division
return x/y;
}
}
package code54;
import java.util.Scanner;
public class TextNumber {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int x = in.nextInt();
int y = in.nextInt();
Number a = new Number(x,y); // Create objects
System.out.println("x+y="+a.addition(x, y)); // Call the addition method
System.out.println("x-y="+a.subtration(x, y)); // Call the subtraction method
System.out.println("x*y="+a.multiplication(x, y)); // Call the multiplication method
System.out.println("x/y="+a.division(x, y)); // Call the division method
}
}
5. Define a rectangle class Rectangle, contain :
(1) attribute
int width;
int height;
(2) Method
Rectangle(): wide 、 High the default value is 1;
Rectangle(int val): wide 、 All heights are parameter values ;
Rectangle(int width,int height):
Double getSquare(): Calculated area ;
Double getPerimeter(): Circumference calculation ;
In addition, write test classes to test .
package code55;
public class Rectangle {
int width;
int height;
Rectangle() // wide 、 High the default value is 1
{
width=1;
height=1;
}
Rectangle(int val) // wide 、 All heights are parameter values
{
width=val;
height=val;
}
Rectangle(int width,int height) {
this.width=width;
this.height=height;
}
Double getSquare() // Calculated area
{
double square;
square=width*height;
return square;
}
Double getPerimeter() // Circumference calculation
{
double c;
c=width*2+height*2;
return c;
}
}
package code55;
import java.util.Scanner;
public class TextRectangle {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println(" Please enter the width and height of the rectangle :");
int width=in.nextInt();
int height=in.nextInt();
Rectangle a=new Rectangle(width, height); // Create objects
System.out.println(" Area is "+a.getSquare()+","+" The perimeter of "+a.getPerimeter()); // Call the method to find the area and perimeter
}
}
6. Define a time class MyTime, There are three properties hour,minute,second. by MyTime Construct method definitions , To initialize member variables when creating objects . In addition to the construction method , Also create the following methods :
(1)nextSecond( ): Time passed 1 second
(2)nextMinute( ): Time passed 1 branch
(3)nextHour( ): Time passed 1 Hours
(4)prevSecond( ): front 1 second
(5)prevMinute( ): front 1 branch
(6)prevHour( ): The last hour
(7)display( ): With HH:MM:SS Format display time
In addition, write test classes , To test .
package code56;
public class MyTime {
int hour;
int minute;
int second;
public MyTime(int hour, int minute, int second) {
this.hour=hour;
this.minute=minute;
this.second=second;
}
void nextSecond() // After a second
{
if(second!=59) second+=1;
else
{
second=0;
if(minute!=59) minute+=1;
else
{
minute=0;
if(hour!=23) hour+=1;
else
{
hour=0;
}
}
}
}
void nextMinute() // After a minute
{
if(minute!=59) minute+=1;
else
{
minute=0;
if(hour!=23) hour+=1;
else
{
hour=0;
}
}
}
void nextHour() // After an hour
{
if(hour!=23) hour+=1;
else
{
hour=0;
}
}
void prevSecond() { // The second before
if(second!=0) second-=1;
else
{
second=59;
if(minute!=0) minute-=1;
else
{
minute=59;
if(hour!=0) hour-=1;
else
{
hour=23;
}
}
}
}
void prevMinute() { // Previous point
if(minute!=0) minute-=1;
else
{
minute=59;
if(hour!=0) hour-=1;
else
{
hour=23;
}
}
}
void prevHour() // The last hour
{
if(hour!=0) hour-=1;
else
{
hour=23;
}
}
void display() // Press HH:MM:SS Time is displayed in the format of
{
System.out.println(hour+":"+minute+":"+second);
}
}
package code56;
import java.util.Scanner;
public class TextMyTime {
public static void main(String[] args) {
int hour=0,minute=0,second=0;
MyTime a=new MyTime(hour,minute,second); // Create an object and assign a value
Scanner in = new Scanner(System.in);
a.hour=in.nextInt();
a.minute=in.nextInt();
a.second=in.nextInt();
a.prevHour();
a.nextMinute();
a.nextSecond(); // Call methods to test
a.display(); // Display the time in the specified format
}
}
7. Write programs using plural classes Complex Verify two complex numbers 2+2i and 3+3i Add to produce a new complex number 5+5i . Plural Complex Meet the following requirements :
(1) attribute
int realPart : The real part of a complex number ;
int imaginPart: The imaginary part of the plural ;
(2) Method
Complex( ) : Construction method , Set both the real and imaginary parts of a complex number to 0;
Complex( int r , int i ) :
Complex complexAdd(Complex a) : Add the current complex object to the formal parameter complex object , The result The result is still a complex value , Return to the caller of this method .
String toString( ) : The real part of the current complex object 、 The imaginary parts are combined into a+bi String form of , among a and b Data of real part and imaginary part respectively .
Write another test class Test, Yes Complex Class to test .
package code57;
public class Complex {
int realPart;
int imaginPart;
Complex() {
realPart=0;
imaginPart=0; // Set both the real and imaginary parts of the complex number to 0
}
Complex(int r,int i) {
realPart=r;
imaginPart=i;
}
Complex complexAdd(Complex a)
{
realPart+=a.realPart;
imaginPart+=a.realPart; // Add the current complex object to the formal parameter complex object
return a;
}
public String toString() // Combine the real and imaginary parts of the current complex object into a+bi String form of
{
return realPart+"+"+imaginPart+"i";
}
}
package code57;
public class TestComplex {
public static void main(String args[]) {
Complex a=new Complex(1,1);
Complex b=new Complex(2,2); // Create an object and assign a value
a.complexAdd(b); // The calling method will a、b Add the two parts of
System.out.println(a.toString()); // Output its combination form
}
}
Summary of experiments
- class : Is a collection of abstract concepts , It represents a common product , Class defines properties and behaviors ( Method );
- object : Object is a representation of personality , Represents an independent individual , Each object has its own independent properties , Rely on attributes to distinguish different objects ;
- stay Java Class , Use keywords class complete ;
- object . attribute : Represents the property in the calling class ;
- object . Method (): Means to call a method in a class ;
- If a constructor has been clearly defined in a class , Then the parameterless constructor will not be automatically generated ;
- this Keywords can be used to call properties of this class 、 Method 、 object .
边栏推荐
- 实验六 继承和多态
- 强化学习基础记录
- FAQs and answers to the imitation Niuke technology blog project (I)
- [面试时]——我如何讲清楚TCP实现可靠传输的机制
- Mortal immortal cultivation pointer-2
- Strengthen basic learning records
- ABA问题遇到过吗,详细说以下,如何避免ABA问题
- 优先队列PriorityQueue (大根堆/小根堆/TopK问题)
- 1143_ SiCp learning notes_ Tree recursion
- Mixlab unbounded community white paper officially released
猜你喜欢
甲、乙机之间采用方式 1 双向串行通信,具体要求如下: (1)甲机的 k1 按键可通过串行口控制乙机的 LEDI 点亮、LED2 灭,甲机的 k2 按键控制 乙机的 LED1
About the parental delegation mechanism and the process of class loading
QT meta object qmetaobject indexofslot and other functions to obtain class methods attention
【手撕代码】单例模式及生产者/消费者模式
UGUI—Text
. How to upload XMIND files to Jinshan document sharing online editing?
3. Input and output functions (printf, scanf, getchar and putchar)
hashCode()与equals()之间的关系
透彻理解LRU算法——详解力扣146题及Redis中LRU缓存淘汰
Principles, advantages and disadvantages of two persistence mechanisms RDB and AOF of redis
随机推荐
ArrayList的自动扩容机制实现原理
UGUI—Text
String abc = new String(“abc“),到底创建了几个对象
强化学习系列(一):基本原理和概念
记一次猫舍由外到内的渗透撞库操作提取-flag
实验七 常用类的使用(修正帖)
Write a program to simulate the traffic lights in real life.
(原创)制作一个采用 LCD1602 显示的电子钟,在 LCD 上显示当前的时间。显示格式为“时时:分分:秒秒”。设有 4 个功能键k1~k4,功能如下:(1)k1——进入时间修改。
Differences among fianl, finally, and finalize
Strengthen basic learning records
HackMyvm靶机系列(5)-warez
强化学习基础记录
canvas基础2 - arc - 画弧线
The difference between cookies and sessions
Difference and understanding between detected and non detected anomalies
[au cours de l'entrevue] - Comment expliquer le mécanisme de transmission fiable de TCP
7-9 制作门牌号3.0(PTA程序设计)
仿牛客技术博客项目常见问题及解答(三)
Miscellaneous talk on May 14
附加简化版示例数据库到SqlServer数据库实例中