当前位置:   article > 正文

面向对象第一章_定义一个食物类food,该类有一属性,即名称 name,定义 showinfo()方法,以便打印显示

定义一个食物类food,该类有一属性,即名称 name,定义 showinfo()方法,以便打印显示

类的定义

类是具有相同属性和方法的一组对象的集合

对象的定义

系统中用来描述客观事物的一个实体,由一组属性和方法构成

方法和属性的概念

方法:对象执行的操作

属性:对象具有的特征

方法重载

1、方法名一样 2、参数列表不一样(参数个数不同或者参数类型不同)

 package com.lenovo.www.demo;
public class Food {
public void food() {
System.out.println("无参的Food");
}
public void food(String a) {
System.out.println("食物的名字是:"+a);
}
public void food(String a,String b) {
System.out.println("食物的中文名是:"+a+"英文名是:"+b);
}
public void food(String name,int num) {
System.out.println("食物的数量为:"+num);
}
public void food(int no,String kind) {
System.out.println("食物的种类为:"+kind);
}
}

eclipse常用快捷键

注释 Ctrl+/    格式化Ctrl+Shift+F   导包Ctrl+Shift+O

其他

实参  调用方法的时候,传递的参数叫实参

形参  定义方法的时候,括号里面的参数叫形参

构造方法

其主要功能是用来在创建对象时初始化对象,即为对象的成员变量赋初值

代码1

  package com.zjm.www.day10;

public class Ex_animal {

public static void main(String[] args) {
// TODO Auto-generated method stub

Animal an1 = new Animal("兔子","草",5);
Animal an2 = new Animal();
Animal an3 = new Animal(an1,an2);
an2.all(an3);
}
}
class Animal{
String name;
String eat;
int weight;
public Animal() {
this.name = name;
this.eat = "猪蹄";
this.weight = 12;
}
public Animal(Animal a,Animal b) {
this.name = b.name;
this.eat = a.eat;
this.weight = b.weight;

}
public Animal(String name,String eat,int weight) {
this.name = name;
this.eat = eat;
this.weight = weight;
}
public Animal(String name,int weight) {
this.name = name;
this.weight = weight;
}
public void eat1() {
System.out.println("这个动物喜欢吃" + this.eat);
}
public void run() {
System.out.println("这个动物会跑");
}
public void all(Animal an) {
System.out.println("这是一只 " + this.name + ",它喜欢吃 " + an.eat + ",它重 " + an.weight +" 斤");
}

}

代码2

package com.lenovo.www.day10;


/**
 * 测试类
 * 
 * @author lenovo64
 *这只小狗是小白,白色正在和那只小猫叫做小黑,黑色在打架
 *获胜的动物是黑色
 */
public class Test {
public static void main(String[] args) {


Animal dog = new Animal("小黑", "小猫", "黑色");
Animal cat = new Animal("小白", "小狗", "白色");
String s = dog.play(cat, dog);
System.out.println("获胜的动物是" + s);
}
}


class Animal {
String name;
String kind;
int age;
String color;
long animalID;
String date;


public Animal(String name, String kind) {
this.name = name;
this.kind = kind;
}


public Animal(String name, String color, String kind) {
this.name = name;
this.color = color;
this.kind = kind;
}


public Animal(String name, int age, long animalID) {
this.age = age;
this.animalID = animalID;
}


public String play(Animal dog, Animal cat) {
System.out.println("这只" + dog.color + "是" + dog.name + "," + dog.kind + ",正在和那只" + cat.color + "叫做" + cat.name
+ "," + cat.kind + ",在打架");
return cat.kind;
}
}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/爱喝兽奶帝天荒/article/detail/1002611
推荐阅读
相关标签
  

闽ICP备14008679号