一、对象

  在讲类之前要先引入对象的概念。对象是类的一个实例,有状态和行为。现在让我们深入了解什么是对象。看看周围真实的世界,会发现身边有很多对象,车,狗,人等等。所有这些对象都有自己的状态和行为。拿一条狗来举例,它的状态有:名字、品种、颜色,行为有:叫、摇尾巴和跑。对比现实对象和软件对象,它们之间十分相似。软件对象也有状态和行为。软件对象的状态就是属性,行为通过方法体现。在软件开发中,方法操作对象内部状态的改变,对象的相互调用也是通过方法来完成。

二、Java中的类

例:

 完整实例:

 1 public class Helloworld {
 2     public static void main(String []args){
 3         /*System.out.println("hello world!");*/
 4         Dog  funny=new Dog("funny");  /*对象实例化*/
 5         funny.setAge(3);
 6         funny.setColor("white");
 7 
 8         funny.sleeping();     /*调用方法*/
 9         funny.getAge();
10         funny.getColor();
11     }
12 static class Dog{ /*定义在类中的类要加static*/ 13 String color; 14 String name; 15 int age; 16 17 public Dog(String name){ /*构造函数,指定name属性*/ 18 this.name=name; 19 } 20 21 void barking(){ 22 System.out.println(name+"is barking!"); 23 } 24 25 void hungry(){ 26 System.out.println(name+"is hungry!"); 27 } 28 29 void sleeping(){ 30 System.out.println(name+"is sleeping!!"); 31 } 32                                  33 public void setAge(int age){ /*set方法*/ 34 this.age=age; 35 } 36 public void setColor(String color){ 37 this.color=color; 38 } 39 public void getAge(){        /*get方法*/ 40 System.out.println(name+" is "+age+" years old!"); 41 } 42 public void getColor(){ 43 System.out.println(name+" is "+color+" !"); 44 } 45 } 46 }

运行结果:

 

posted on 2020-04-11 15:23  A_yun  阅读(156)  评论(0编辑  收藏  举报