标签:sys 苹果 import width uil points 换行 build app
继承是面向对象编程技术的主要特征之一,也是实现软件复用的重要手段,使用继承特性子类(subclass)
可以继承父类(superclass)中private方法和属性,继承的目的是使程序代码重用,减少冗余。
1.1 类的继承的实现
·java语言中子类对父类的继承是通过在子类定义时,使用关键字extends来实现的;
·如果定义一个java类时并未显示的指定这个类的直接父类,则这个类默认继承java.land.Object类
·继承的特点,子类中的对象可以使用父类中的非private成员(方法和变量),故在子类中不必重写,这就是继承。
/**
* Created by qichunlin on 2017/10/10.
*/
public class Fruit {
public String fruitName;
public double weight;
public void info()
{
System.out.print("我是一个"+fruitName+"~重"+weight+"g!");
}
}
public class Apple extends Fruit{
public static void main(String[] args){
Apple a=new Apple();
a.fruitName="苹果";
a.weight=200;
a.info();
}
}
·定义:是指在一个类中用相同的方法名字定义多个方法,当然每个方法应该具有不同的代码,以实现不同的功能
方法的重载是实现多态性的重要手段。
·方法的名称、类型和形式参数构成了方法的签名,编译器根据方法的签名确定使用的是什么方法,因此方法的签名必须唯一。方法的返回值类型对方法的签名没有影响,因此方法没有返回值
2.2 看下面一个例子
/**
* Created by qichunlin on 2017/10/5.
*/
/**
定义一个矩形类MyRect,重载buildRect方法
描述一个矩形,如:可使用矩形的左上角和右下角坐标,使用两个点类的对象point,
* */
import java.awt.Point;
class MyRect //定义矩形类
{
int x1=0; //左上角坐标初始化
int y1=0;
int x2=0; //右下角坐标初始化
int y2=0;
MyRect buildRect(int x1,int y1,int x2,int y2) //方法1,左上角和右下角
{
this.x1=x1;
this.y1=y1;
this.x2=x2;
this.y2=y2;
return this;
}
MyRect buildRect(Point topLeft,Point bottomRight) /*方法2,两个point‘对象,指定左上角和右下角坐标*/
{
x1=topLeft.x;
y1=topLeft.y;
x2=bottomRight.x;
y2=bottomRight.y;
return this;
}
MyRect buildRect(Point topLeft,int w,int h)
//方法3,左上角和宽度与高度
{
x1=topLeft.x;
y1=topLeft.y;
x2=(x1+w);
y2=(y1+h);
return this;
}
void printRect() //打印输出坐标
{
System.out.print("MyRect:<"+x1+","+y1); //打印后不换行
System.out.print(","+x2+","+y2+">"); //继续上行打印
}
public static void main(String[] args)
{
MyRect rect=new MyRect(); //创建对象
System.out.print("Calling buildRect with coordinates 25,25,50,50:"); //创建矩形1,调用方法1
rect.printRect(); //打印出坐标
System.out.print("* * *");
System.out.println("Calling buildRect with points (10,10),(20,20):"); //矩形2,调用方法2
rect.buildRect(new Point(10,10),new Point(20,20));
rect.printRect(); //打印出坐标
System.out.println("* * *");
System.out.print("Calling buildRect with 1 point(10,10),");
System.out.println("width(50)and height(50):");
rect.buildRect(new Point(10,10),50,50); //矩形3,调用方法3
rect.printRect(); //打印出坐标
System.out.println("* * *");
}
}
例子2:
/**
* Created by qichunlin on 2017/10/7.
*/
class MethodOverloading
{
void receive(int i)
{
System.out.println("Received one int data");
System.out.println("i="+i);
} void receive(float f)
{
System.out.println("Received one float data");
System.out.println("f="+f);
}
void receive(String s)
{
System.out.println("Received a String");
System.out.println("s="+s);
}
public static void main(String [] args)
{
MethodOverloading m = new MethodOverloading();
m.receive(3456);
m.receive(34.56f);
m.receive("方法重载");
}
}
3.方法的重写
方法的重写是指在子类中使用与父类
2017.10.10 java程序设计-------继承与多态
标签:sys 苹果 import width uil points 换行 build app
原文地址:http://www.cnblogs.com/qichunlin/p/7646721.html