类和对象
对象:万物皆对象,现实当中存在的东西皆是对象。真正看的到摸得着的具体实体,真正干活的也是对象。
类:模型,确定对象将会拥有的特征(属性)和行为(方法),一种概念,一种模型。
--对象是类的实例化表现
--类是对象的类型
--对象是特定类型的数据。
先定义类---->通过类,实例化对象
属性和方法
属性:对象拥有的各种静态特征。
方法:对象具有的各种动态行为
创建类和实例化对象
创建类
众所周知java面向对象编程的大概思路是:根据需求-->创建类--->根据类实例化对象,实现需求
创建包
包的命名规范倒着写的域名
在包里面创建类
类的命名规则如CatTest
以下是创建类的例子:
package com.company;
/*
*宠物猫类
* @auther dongdong
* */
public class Cat {
//成员属性:昵称、年龄、体重、品种
String name;//名字
int month;//年龄
double weight;
String species;
//方法:跑、吃东西
//跑动的方法
public void run(){
System.out.println("小猫快跑");
}
public void run(String name){
System.out.println(name+"快跑");
}
//吃东西的方法
public void eat(){
System.out.println("小猫吃鱼");
}
}
实例化对象
根据创建好的类,创建CatTest测试我们写好的Cat类
package com.company;
public class CatTest {
public static void main(String[] args){
//对象实例化
Cat one = new Cat();
//测试方法
one.eat();
one.run();
//测试属性
System.out.println(one.name);
System.out.println(one.month);
System.out.println(one.species);
System.out.println(one.weight);
System.out.println("对象初