1-1 导学
稳定性,可扩展性,可重用性
1-2 类和对象
类是模型,确定对象将会拥有的特征(属性)和行为(方法)
对象是类的实例表现
类是对象的类型
对象是特定类型的数据
属性:对象具有的各种静态特征
-“对象有什么”
方法:对象具有的各种动态行为
-“对象能做什么”
1-3 创建类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| package com.imooc.animal;
public class Cat { String name; int month; double weight; String species;
public void run() { System.out.println("小猫快跑"); }
public void eat() { System.out.println("小猫吃鱼"); } }
|
1-4 实例化对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| package com.imooc.animal;
public class CatTest { public static void main(String[] args) { Cat one=new Cat(); one.eat(); one.run(); one.name="花花"; one.month=2; one.weight=1000; one.species="英国短毛猫"; System.out.println("昵称:"+one.name); System.out.println("年龄:"+one.month); System.out.println("体重:"+one.weight); System.out.println("品种:"+one.species); } }
|
1-5 单一职责原则
单一职责原则:有且只有一个引起功能变化的原因。
如果在一个类当中,承担的功能越多,交融、耦合性就越高,被复用的可能性就越低。
由于耦合性高,一个职责变化的时候,很可能引起其他功能的变化。
在程序设计,将不同功能分装到不同的类中。这就是一种职责单一的表现。
1-6 new关键字
对象实例化
实例化对象的过程可以分为两部分:
-声明对象 Cat one
-实例化对象 new Cat();
Cat one=new Cat();
//在栈里开辟了一个内存空间是one 在堆中开辟了一个空间 然后将堆中的这个空间内存地址 放到了one里面
Cat two=one;
//将one中的内存地址复制了一份放到了two里面
这时one和two都对该内存空间有了指向的操作权
首先对one进行赋值,写入堆的内存,当对two进行赋值的时候覆盖了原来one的赋值
1-7 编程练习
编写自定义Person类,根据提示以及效果图补全编辑器中代码。
程序运行参考效果图如下:
1 2 3
| 我是一名学生! 我是一个男孩! 我叫李明,今年10岁了,读小学五年级了。
|
任务:
- 创建Person类
属性:名字(name),年龄(age),年级( grade)
方法:1、无参无返回值的student方法,描述为:我是一名学生!
2、带参数(性别sex)的方法,描述为:我是一个xx孩!(其中,xx为传入参数)
3、无参无返回值的mySelf方法,介绍自己的姓名、年龄、年级(参数参考效果图)
- 创建测试类
实例化对象,传入参数,调用无参无返回值的student和mySelf方法及带参方法sex
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| public class Person { String name; int age; String grade;
public void student(){ System.out.println("我是一名学生!"); }
public String sex(String sex){ System.out.println("我是一个"+sex+"孩!"); return sex; }
public void mySelf(){ System.out.println("我叫"+name+",今年"+age+"岁了,读小学"+grade+"年级了。"); }
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public class Test {
public static void main(String[] args) { Person one=new Person(); one.name="李明"; one.age=10; one.grade="五"; one.student(); one.sex("男"); one.mySelf(); }
}
|