类
一.面向对象概述
面向对象编程:是指将现实世界中的概念模拟到计算机程序中,他将现实世界中的所有事物视为对象,对象具有属性和行为。
面向对象编程思想的核心是对象,对象是指现实世界中的实体,OOP能够将现实世界中的实体模拟为计算机上的类似实体。
二.类和对象的相关概念
多个对象所共有的属性和操作需要组合成一个单元称为“类”。
1.类的定义
类似具有相同特征和共同行为的一组对象集合。
类定义了对象所拥有的特征(属性)和行为(方法),定义了一种对象所能拥有的数据和能完成的操作,在面向对象的程序设计中,类是程序的基本单元,程序中的对象是类的一个实例,是一个软件单元,由一组结构化的数据和在其上的一组操作构成。
构成对象的两个最重要的因素就是特征(属性)和行为(方法)。
1)类的属性
对象或者实体的特征在类中表示为成员变量,称为类的属性。
属性的定义:对象或实体拥有的特征在类中的表示称为属性。
2)类的方法
方法是对象执行操作的一种规范。方法用于指定以何种方式操作对象的数据,是操作的实际实现。
方法的定义:对象执行的操作称为方法。
2.类和对象的区别
类和对象是有本质区别的:类是用来描述实体的“模板”或“原型”,而对象是实际的实体,每一个对象都是类的一个实例。
对象是实体,而类是概念模型,用来定义对象的所有特征和所需操作。
(1)类似对象的“原型”,它为特定类型的对象指定了允许的操作和必要的特征。
(2)类似对象的类型
三.定义一个类的步骤
类将现实世界中的概念模拟到计算机程序中,类是对象的模型,确定对象拥有的特征(属性)和行为(方法),因此,定义一个类需要抽取同一种对象的属性和方法的共同特征。
(1)定义类名
Public class 类名
{
//程序体
}
(2)编写类的属性
(3)编写类的方法
class Person
{
//定义属性
String name;
int age;
//定义方法
public void hello( )
{
String.out.println(“喂,你好,我的名字叫”+name+",今年"+age+“岁!”);
}
}
四.代码片
下面展示一些 类的代码片
。
package com.hg.demo02;
public class phone {
String brand;
double price;
String color;
public void call(String who) {
System.out.println("给"+who+"打电话");
}
public void sendMessage() {
System.out.println("群发短信");
}
}
package com.hg.demo02;
public class Demo01phoneOne {
public static void main(String[] args) {
phone one=new phone();
System.out.println(one.brand);
System.out.println(one.price);
System.out.println(one.color);
System.out.println("=============");
one.brand="华为";
one.price=8388.0;
one.color="土豪金";
System.out.println(one.brand);
System.out.println(one.price);
System.out.println(one.color);
one.call("任正非");
one.sendMessage();
phone two=new phone();
System.out.println(two.brand);
System.out.println(two.price);
System.out.println(two.color);
System.out.println("=============");
two.brand="小米华为";
two.price=1999.0;
two.color="白色";
System.out.println(two.brand);
System.out.println(two.price);
System.out.println(two.color);
two.call("雷布斯");
two.sendMessage();
}
}
package com.hg.demo01;
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("小袁爱学习!");
}
}
package com.hg.demo01;
public class Demo02Student {
public static void main(String[] args) {
Student stu=new Student();
System.out.println(stu.name);
System.out.println(stu.age);
stu.name="袁雪华";
stu.age=18;
System.out.println(stu.name);
System.out.println(stu.age);
stu.eat();
stu.sleep();
stu.study();
}
}