面向对象编程(Object Oriented Programming,OOP,面向对象程序设计)是一种计算机编程架构。OOP 的一条基本原则是计算机程序是由单个能够起到子程序作用的单元或对象组合而成。
OOP: Object Oriented Programming,面向对象的程序设计。所谓“对象”在显式支持面向对象的语言中,一般是指类在内存中装载的实例,具有相关的成员变量和成员函数(也称为:方法)。面向对象的程序设计完全不同于传统的面向过程程序设计,它大大地降低了软件开发的难度,使编程就像搭积木一样简单,是当今电脑编程的一股势不可挡的潮流。
OOP 达到了软件工程的三个主要目标:重用性、灵活性和扩展性。为了实现整体运算,每个对象都能够接收信息、处理数据和向其它对象发送信息。
//opp面向过程编程。
//关注的是事情本身,解决问题一共分为几步,逐步完成每一个环节
//最终解决问题。
//oop面向对象编程。
//关注的重心是 参与某件事情的对象,而不是事情本身。
//面向对象的核心是如何设计这些对象。
//类:是对相同事物的抽象和提炼。
//对象:对象是类具体体现。
//类如何去形容事物呢?
//特征和行为
//特征:描述特点,称为属性。
//行为:描述功能,称为方法
//一个类包含2部分内容:特征(属性)、行为(方法)
//修饰符 class 类名{
// 修饰符 类型 属性名 [= 初始值];
//…
// 修饰符 返回值类型 方法名(参数列表){
// 方法体;
// }
//}
//有了类之后,我们就可以创建对象了。
//类型(类名) 变量名 = new 类型() ;
package com.lanou3g.demo1;
public class Person {
//特征(属性)
public String name; //姓名
public String sex; //性别
public int age; //年龄
//行为(方法)
public void eat() {
//吃饭
System.out.println("吃饭");
}
public void sleep() {
//睡觉
System.out.println("睡觉");
}
public void study() {
//学习
System.out.println("学习");
}
}
新的类里面创建一个对象
public class TestObject {
public static void main(String[] args) {
/*
//创建一个对象。
Person p = new Person();
//当有了具体对象以后,我们就可以访问对象的属性以及
//对象的方法了。
//访问属性: 对象.属性
//设置属性的值
//把对象p的姓名设置成 张三
p.name = "张三";//注意:值的类型必须与属性的类型一致。
//读取属性的值
//例如 打印 p的姓名
System.out.println(p.name);
//把p的性别设置为 男 年龄设置为22.
p.sex = "男";
p.age = 22;
//打印p的 年龄和性别
System.out.println(p.age);
System.out.println(p.sex);
//对象访问方法---对象调用方法。
//语法格式:对象.方法名(参数);
p.eat();
p.sleep();
p.study();
Person p1 = new Person();
p1.name = "李四";
p1.age = 23;
Person p2 = new Person();
p2.name = "王五";
*/
Rect rect1 = new Rect();
rect1.x = 30;
rect1.y = 20;
rect1.width = 20;
rect1.height = 10;
System.out.println(rect1.area());
System.out.println(rect1.perimeter());
System.out.println(rect1.isSquare());
}
}
//变量的作用域:变量起作用的区域。
//局部变量,块变量
//局部变量:在 方法内 定义的变量称为局部变量。
//作用域:从定义的那一行开始,一直到所在的方法结束。
//块变量:在 一对{}里面定义的变量。
//作用域:从定义的那一行开始,一直到所在的大括号结束。