面向对象
“对象”包括三方面内容:对象名称,对象属性,对象操作;
面向对象其实就是“那东西来干活”
1.对象的名称。每个对象的名称都不一样
2.对象的属性:不同的对象不同属性
3.对象操作:值对象能进行的行为
创建对象:
1.声明:
类名 对象名;
例如:Car c1,c2;
Float f1,f2;
2.创建对象
对象名称 = new 类构造方法名([实际参数列表]);
1.new运算会为对象分配空间,并调用构造方法,获得对象的引用
2.类构造方法名就是类名
3.实际参数列表;注意:实参可以是常量,变量,表达式,函数等,个数,类型,顺序都应该与形参一一对应。即使没有实参也不能省略括号
声明对象和创建对象可以合并;如下
类名 对象名 = new 类构造方法名([实际参数列表]);
例如:Car c1 = new Car("红旗",“黑色”);
3.引用对象
语法格式:对象名.成员变量名;
应用成员方法的语法格式如下:
对象名字.成员方法名([实际参数列表]);例如:
假如开始给某些属性赋值负错了,可以用下面语句更正:
例子:c2.color="红色";
这样做可以覆盖掉你上一次的赋值;
4.对象的使用
public class Point {
//声明int型变量num1
public int num1 = 0;
public int num2 = 0;
public String x;
public String y;
public Point(int x,int y){
num1=x;
num2=y;
}
}
public class Rectangle {
public int width =0;
public int length = 0;
public Point origin;
public Rectangle(){
origin = new Point(0,0);
}
public Rectangle(Point p){
origin = p;
}
public Rectangle(int num1,int num2){
origin = new Point(0,0);
width = num1;
length = num2;
}
public Rectangle(Point p,int num1,int num2){
origin = p;
width = num1;
length = num2;
}
public void move(int num1,int num2){
origin.num1=num1;
origin.num2=num2;
}
public int getArea(){
return width*length;
}
}
public class ObjectOperation {
public static void main(String[] args){
Point po = new Point(11,22);
Rectangle rectangle = new Rectangle(po,20,10);
Rectangle rectangle1 = new Rectangle(20,10);
System.out.println("rectangle1的宽为:"+rectangle.width);
System.out.println("rectangle1的长为:"+rectangle.length);
System.out.println("rectangle1的面积为:"+rectangle.getArea());
rectangle1.origin = po;
System.out.println("X坐标是:"+rectangle1.origin.x);
System.out.println("Y坐标是:"+rectangle1.origin.y);
}
}
与逆行结果为:
先写那么多了,面向对象是比较重要的知识点,内容也比较多,我就先写到这,下次再继续~
下一篇应该会写关于面向对象的三大特征:封装,继承,多态。