java封装将代码及其处理数据绑定在一起的编程机制,保证程序和数据不受外界干扰和误用,想成一个黑匣子,给一个输出出现结果,不用考虑内部的实现。
java继承一个对象获取令一个对象的属性,使其成为更通用的实例的类。
1.写一个父类,里面拥有一些属性。
public class Animal { private Double weight; private String color; private String type; /** * @return the weight */ public Double getWeight() { return weight; } /** * @param weight the weight to set */ public void setWeight(Double weight) { this.weight = weight; } /** * @return the color */ public String getColor() { return color; } /** * @param color the color to set */ public void setColor(String color) { this.color = color; } /** * @return the type */ public String getType() { return type; } /** * @param type the type to set */ public void setType(String type) { this.type = type; } public Animal(Double weight, String color, String type) { this.weight = weight; this.color = color; this.type = type; } }
2.子类继承父类,并添加一些自己的属性。
public class Dog extends Animal { private String name; /** * @return the name */ public String getName() { return name; } public void action(int i){ if (i==1) { System.out.println("跑步"); }else { System.out.println("溜达"); } } /** * @param name the name to set */ public void setName(String name) { this.name = name; } public Dog(Double weight, String color, String type,String name) { super(weight, color, type); this.name=name; } public static void main(String[] args) { Dog a=new Dog(11d, "color", "狗", "阿拉斯加"); System.out.println(a.name); a.getType(); a.action(1); a.action(344); } }
二.多态