1.方法的重载:指的是在同一个类中,方法名相同,方法的参数不同,方法的返回类型不参与比较
代码实列:
package day1;
//使用方法重载求矩形的面积,而正方形与长方形又有不同
public class Area {
public static void main(String[] args) {
Area s=new Area();
System.out.println("边长是4的正方形的面积:"+s.area(4));
System.out.println("边长是4和6的长方形的面积:"+s.area(4,6));
}
public double area(double a) {
return a*a;
}
public double area(double a,double b) {
return a*b;
}
}
初次理解类的抽象:
代码实列:
package day1;
/*1.编写Point类,有两个属性x,y,一个方法distance(Point p1,Point p2)来计算两点之间的距离
*2.分析:类是抽象的,无论哪一个点(对象)的坐标都有x,y坐标(两个成员变量)
* 所以不是定义四个变量x1,x2,y1,y2;
*3.想要使用ditance方法,要在main方法中建立两个对象
*4.需要用到数学类Math下的一些方法
* */
public class Point {
double x;
double y;
public Point(double x, double y) {//构造方法
super();
this.x = x;
this.y = y;
}
public double distance(Point p1,Point p2) {
return Math.sqrt(Math.pow(p1.x-p2.x,2))+Math.sqrt(Math.pow(p1.y-p2.y,2));
}
public static void main(String[] args) {
Point p1=new Point(5,3);
Point p2=new Point(4,2);
//System.out.println(Point.distance(p1,p2));
//distance 定义为静态方法,可以直接类名调用;
System.out.println(p1.distance(p1,p2));
}
}
初次较快地打出构造方法,set 和 get方法,初次写对象数组
代码实列:
package day1;
/*题目要求:
* 创建一个Flower类,包含四个成员变量:name,type,color,price
* 每个成员变量都用get方法返回对应的属性值,然后创建三个Flower对象:
* 1.玫瑰花,第一,紫色,400
* 2.玫瑰花,第二,红色,300
* 3.百合花,第三,橙色,200
* 把三个对象存储在一个数组中,最后遍历数组读取各个对象的属性值
* 分析:
* 数组中的每个元素都是Flower类型的对象,即对象数组
* */
public class Flower {
String name;
String type;
String color;
double price;
public Flower(String name, String type, String color, double price) {
super();
this.name = name;
this.type = type;
this.color = color;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public static void main(String[] args) {
Flower f1=new Flower("玫瑰花","第一","紫色",400);
Flower f2=new Flower("玫瑰花","第二","红色",300);
Flower f3=new Flower("百合花","第一","橙色",240);
Flower f[]=new Flower[3];//对象数组,此时每个对象还是空对象
f[0]=f1;
f[1]=f2;
f[2]=f3;
for(int i=0;i<f.length;i++)
{
System.out.println(f[i].getName()+" "+f[i].getType()+" "+f[i].getPrice());
}
}
}