第21集 对象的转型
1)对象的向上转型.
向上转型: 将子类的对象赋值给父类的引用.
Student s = new Student();
Person p = s; //向上转换.子类的对象赋值给父类的引用.
向上转型是一定可以成功.
2)对象的向下转型:
向下转型--将父类的对象赋值给子类的引用.
Student s1 = new Student();
Person p = s1;
Student s2 = (Student)p;
向下转型的前提是 先进行了向上转型。
class Person{
String name;
int age;
void introduce(){
System.out.println("我的名字"+ name+"年龄"+age);
}
}
class Student extends Person20{
String address;
void study(){
System.out.println("学习");
}
void introduce(){
//anotherFun();
super.introduce();//调用父类的成员函数,减少重复代码,
//System.out.println("我的姓名是"+name+"我的年龄是"+age);
System.out.println("我的家在"+address);
}
}
//一个引用能够调用哪些成员(变量和函数),取决于这个引用的类型
//一个引用调用的是哪一个方法,取决于这个引用指向的对象.
class Test{
public static void main(String args[]){
//正确的向下转型
Person p = new Student();
Student s = (Student)p;
//错误的向下转型
//Person p = new Person();
//Student s = (student)p;
//向上转型
//Student s = new Student();
//Person p = s;
//p.name = "张三";
//p.age = ;
//p.address = "北京"; //此语句不能执行
//一个引用能够调用那些成员(变量和函数),取决于这个引用的类型
//p.introduce();//调用子类的的introduce()
//一个引用调用的是那一个方法,取决于这个引用指向的对象.
}
}
第22集 面向对象应用
被客户不断变化的需求"折磨".
class Printer{
void open(){
System.out.println("open");
}
void close(){
System.out.println("close");
}
void print(String s){
System.out.println("print---->"+ s );
}
}
class HPPrinter extends Printer{
}
class CanonPrinter extends Printer{
void close(){
this.clean();
super.close();
}
void clean()
{
System.out.println("clean.................");
}
}
class TestPrinter{
public static void main(String args[]){
int flag =1;
if( flag==0)
{
HPPrinter Hprinter = new HPPrinter();
Hprinter.open();
Hprinter.print("abcdefg");
Hprinter.close();
}
else if(flag==1)
{
CanonPrinter canonprinter = new CanonPrinter();
canonprinter.open();
canonprinter.print("abcdefg");
canonprinter.close();
}
}
}
这是一个打印机的例子,程序中有两个类型的打印机,它们的方法有些不一样。