软件出现的目的
用计算机的语言描述现实世界
用计算机解决现实世界的问题
为什么使用面向对象
世界由对象组成
面向对象的思想 描述 面向对象的世界 符合人类思维习惯
从现实中抽象出类分三步:
- 找出它的种类
- 找出它的属性
- 找出它的行为
用面向对象描述世界
第一步:发现类
class Dog
{
}
根据“对象”抽象出“类”
第二步:发现类的属性
狗类共有的特征:
- 品种
- 年龄
- 昵称
- 健康情况
- 跟主人的亲密度
… …
class Dog {
String name = "旺财"; // 昵称
int health = 100; // 健康值
int love = 0; // 亲密度
String strain = "拉布拉多犬"; // 品种
}
只放和业务相关的属性
第三步:发现类的方法
狗类共有的行为:
- 跑
- 吠
- 输出自己的信息
… …
使用类图描述类
eg.实现领养宠物功能
编写宠物类Dog和Penguin
创建宠物对象,输入领养的宠物信息并输出
对象初始化
cat scat=new cat();
scat.name = "haha";
scat.sex = "girl";
能否在创建对象的同时就完成赋值?
class cat {
// 属性
/* 无参构造方法 */
public cat() {
name = "haha";
love = 20;
sex = "girl";
System.out.println("执行构造方法");
}
}
import cn.bank.Dog;
public class swap {
public static void main(String[] args) {
System.out.println ("欢迎您来到宠物店");
System.out.println ("请输入要领养的宠物的名字");
Scanner scanner=new Scanner( System.in);
String name=scanner.next();
System.out.println ("请选择要领养的宠物的类型:1.狗狗 2.企鹅");
int type=scanner.nextInt ();
if(type ==1)
{
Dog d = new Dog();
System.out.println ("请选择狗狗的品种:1.聪明的拉布拉多 2.酷酷的雪纳瑞");
int kind=scanner.nextInt ();
d.setKind ( kind );
d.setName ( name );
System.out.println (d);
}
else
{
System.out.println ("我是一只萌萌哒企鹅");
}
}
}
package cn.bank;
public class Dog {
private String name = "sunny";
private int health = 100 ;
private int love = 0;
private int type;
private int kind;
public String toString()
{
String strkind = "";
if(kind == 1)
{
strkind = "拉布拉多" ;
}
else if(kind == 2)
{
strkind = "雪纳瑞" ;
}
String str = "宠物的自白,我的名字叫" + name +"健康值是" + health
+"和主人的亲密度是" + love + "我是一只" +strkind;
return str;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getHealth()
{
return health;
}
public void setHealth(int health)
{
this.health = health;
}
public int getLove()
{
return love;
}
public void setLove(int love)
{
this.love = love;
}
public int getType()
{
return type;
}
public void setType(int type)
{
this.type = type;
}
public int getKind()
{
return kind;
}
public void setKind(int kind)
{
this.kind = kind;
}
}