/** * 方法定义——重载 * 方法定义——static * 没有自定义构造方法时,编译器会自动加一个无参构造方法 * 构造方法之间的调用——this */ public class Dog { public String name; private int age; public int weight; //无参构造方法 public Dog(){ //this 调用带三个参数的构造方法 this("黑宾",15,15); } //带两个参数构造方法 public Dog(int age,String name){ this.age = age; this.name = name; } public Dog(String name,int age,int weight){ this.age = age; this.name = name; this.weight = weight; this.run();//构造方法里可以访问各种普通方法 } public void setAge(int a){ this.age = age; } public int getAge(){ return age; } public void run(){ System.out.println(name+"狗跑了。。。"); } public void mesage(String name,int age){ System.out.println("狗的名字为:"+name+",年龄为:"+age); } public void mesage(String name,int age,int weight){ System.out.println("狗的名字为:"+name+",年龄为:"+age+",体重为:"+weight); } protected void action(){ System.out.println(name+"狗很听话,能根据指令进行相应的动作"); } public static void human(){ System.out.println("主人找到了狗"); } }
public class Animal { public static void main(String[] args) { //无参构造方法对象 Dog obt = new Dog(); //this 调用方法传出的值 Dog abc = new Dog(); System.out.println(abc.name+abc.getAge()+abc.weight); obt.name = "小黑"; obt.weight = 15; obt.setAge(5); obt.mesage("小白",6); obt.mesage("小黄",4,12); obt.run(); obt.action(); //obt.human(); Dog.human(); //有参构造方法 Dog oca = new Dog(15,"小蓝"); System.out.println("名字为"+oca.name+",年龄为"+oca.getAge()); } }
/** * 面向对象属性定义 * public,private,protected * this使用 * static使用 */ public class Employee { public String name; //private需要用set和get方法进行赋值和取值 private int age; //static定义的属性需要用(类名.属性名调用) public static float height; //protected定义的变量和类在同一个包中可以访问 protected double sal; int sex; String habit; //赋值 public void setAge(int a){ //this来区别参数和属性名,后面是属性名或方法名 //this代表当前对象自身 this.age = a; } //取值 public int getAge(){ return age; } public void play(){ System.out.println("我喜欢打"+habit); } }
public class EmployDemo { public static void main(String[] args) { Employee obt = new Employee(); obt.name = "张三"; obt.sex = 1; obt.habit="篮球"; obt.play(); obt.setAge(100); System.out.println("年龄为:"+obt.getAge()); obt.sal=10000; //obt.height=174.1f;虽然可以使用,但是访问的变量都是同一份 Employee.height = 179F; } }