面向对象有3大特征:封装,继承,多态
继承:父子概念的继承:圆继承于图形
圆是子概念(子类型Sub class)图形是父类型(Super Class)
继承在语法方面的好处:子类共享了父类的属性和方法的定义,子类复用了父类的属性和方法。节省了代码。
继承体现了多态:父类型变量可以引用各种各样的子类型实例
个体的多态:父类型的子类型实例是多种多样的
行为的多态:父类型定义方法被子类重写为多种多样的,重载也是多态的方法。
package day2;
/*
* 图形 类型 其中x,y代表图形的位置
* 图形作为父类型,被圆和矩形继承
*/
public class Shape {
int x;
int y;
//图形向上移动的方法
public void up(int dy){
y -= dy;
}
public void up(){
y -- ;
}
/*检查当前图形是否包含(contains)坐标(x,y)*/
public boolean contains(int x,int y){
return false;
}
}
package day2;
/*
* 圆继承了图形,表示圆是一个图形。
* 圆会自动继承父类型的属性和方法
* 其中:Shape称为父类型(super class)
* Circle称为子类型(Sub class)
*/
public class Circle extends Shape{
int r;
public Circle(int x,int y,int r){
this.x = x;//this.x从父类继承的属性
this.y = y;
this.r = r;
}
//计算当前圆对象的面积
public double area(){
return 3.14 * this.r *this.r;
}
/*重写(覆盖)了父类的方法*/
public boolean contains(int x,int y){
int a = this.x-x;
int b = this.y -y;
double c = Math.sqrt(a*a+b*b);
return c
关注
打赏