Java面向对象思想,类和对象的区别,用法。

it2024-01-02  56

1、面向对象思想概述

面向过程:当需要实现一个功能的时候,每一个具体的步骤都要亲力亲为,详细处理每一个细节。 面向对象:当需要实现一个功能的时候,不关心具体的步骤,而是找一个已经具有该功能的人,来帮我做事儿。 例如:

public static void main(String[] args) { int[] array = {10, 20, 30, 40, 50}; //要求打印格式为:[10, 20, 30, 40, 50] //使用面向对象过程 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("---------"); //面向对象 System.out.println(Arrays.toString(array)); }

面向过程:强调步骤 面向对象:强调对象。 面向对象思想是一总更符合我们思考习惯的思想,它可以将复杂的事情简单化,并将我们从执行者变成了指挥者。面向对象的语言中,包含了三大基本特征,即封装、继承、多态。

2、类和对象

类:是一组相关属性和行为的集合,可以看成是一类事物的模板,使用事物的属性特征和行为特征来描述该类事物 对象:是一类事物的具体表现。对象是类的一个实例,必然具备该类事物的属性和行为。 类是对一类事物的描述,是抽象的。 对象是一类事物的实例,是具体的。 类是对象的模板,对象是类的实体。 创建一个简单的Phone对象: 在同一个包下的另一个类调用类创建对象,给对象以及通过对象调用Phone类定义的方法。 类和对象的简单用法如上。

使用对象类型作为方法的参数:

public static void main(String[] args) { Phone one = new Phone(); one.band = "iPhone 12"; one.color = "白色"; one.worth = 6299; method(one); //传递进去的参数其实就是地址值 } public static void method(Phone param) { System.out.println(param.worth); System.out.println(param.color); System.out.println(param.band); }

使用对象类型作为方法的返回值:

public static void main(String[] args) { Phone two = getPhone(); System.out.println(two.band); System.out.println(two.color); System.out.println(two.worth); } public static Phone getPhone() { Phone one = new Phone(); one.worth = 6299; one.color = "白色"; one.band = "iPhone 12"; return one; }
最新回复(0)