1.面向对象的思想
(1)面向过程:当需要实现一个功能的时候,每一个具体的步骤都要亲历亲为,详细处理每一个细节。
(2)面向对象:当需要实现一个功能的时候,不关心具体的步骤,而是找一个已经具有该功能的人,来帮助我做事。
import java.util.Arrays;
public class Demo01PrintArray {
public static void main(String[] args) {
int[] array ={10,20,30,40};
//要求打印格式为:{10,20,30,40}
//使用面向过程:每个步骤亲历亲为。
System.out.print("[");
for (int i = 0; i < array.length; i++) {
if (i == array.length - 1) {
System.out.println(array[i] + "]");
} else {
System.out.print(array[i] + ",");
}
}
System.out.println("=====================");
//面向对象:找一个jdk给我们提供好的Arrays这个类型,其中有一个toString方法,可以
//把数组变成想要的格式的字符串。
System.out.println(Arrays.toString(array));
}
}
2.类和对象
(1)类:是一组相关属性和行为的集合。属性(是什么);行为(能做什么)。
(2)对象:是一类事物的具体体现
(3)类和对象的关系
通常情况下,一个类并不能直接使用,需要根据类创建一个对象,才能使用。
(4)类的定义
/*
定义一个类,用来模拟“学生”事物,其中由两部分组成
成员变量(属性)
成员方法(行为)
*/
public class Student {
//成员变量
String name;//姓名
int age;
//成员方法
public void eat(){
System.out.println("吃饭");
}
public void sleep(){
System.out.println("睡觉");
}
public void study(){
System.out.println("学习");
}
}
注意:普通的方法有static,成员方法没有。
(4)对象的创建和使用
/*
创建对象的步骤
1.导包,也就是需要指出需要使用的类在什么位置。
import 包名称.包名称;
对于和当前类使用同一个包的情况,可以省略导包语句。
2.创建
格式:类名称 对象名 =new 类名称();
3.使用
分两种情况
使用成员变量: 对象名.成员变量名
使用成员方法:对象名.成员方法名(参数)
注意事项:
如果成员对象没有赋值,那么将会有一个默认值,规则和数组一样。
*/
public class Demo02Student {
public static void main(String[] args) {
//创建
//根据Student类,创建了一个名为stu的对象。
Student stu= new Student();
System.out.println("=====");
System.out.println(stu.name);
System.out.println(stu.age);
stu.name = "杨幂";
stu.age = 24;
System.out.println(stu.name);
System.out.println(stu.age);
}
}
3.手机类练习
(1)首先定义一个类
/*
定义一个类,用来模拟“手机”事物。
成员变量(属性):
成员方法(行为):
*/
public class Phone {
//成员变量
String brand;
double price;
String color;
//成员方法
public void call(String who){
System.out.println("给"+who+"打电话");
}
public void sendMessage(){
System.out.println("群发短信");
}
}
(2)根据类型创建一个对象
public class Demo01Phone {
public static void main(String[] args) {
//根据Phone类,创建对象。
Phone one = new Phone();
System.out.println(one.brand);
System.out.println(one.color);
System.out.println(one.price);
System.out.println("=============");
one.brand = "苹果";
one.price = 8200.2;
one.color = "黑色";
System.out.println(one.brand);
System.out.println(one.color);
System.out.println(one.price);
System.out.println("==============");
one.call("马云");
one.sendMessage();
}
}