- 1、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
- 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
例8.9运算符instanceof及getName()、getSuperclass()方法的使用。
//filename Person.java
public class Person //定义person类
{
static int count=0;
protected String name;
protected int age;
public Person(String n1,int a1)
{
name=n1;
age=a1;
this.count++; //调用父态的静态变量
}
public String toString()
{
return this.name+,+this.age;
}
public void display()
{
System.out.print(本类名=+this.getClass().getName()+;);
System.out.println( 父类名=+this.getClass().getSuperclass().getName());
System.out.print(Person.count=+this.count+ );
System.out.println( Student.count=+Student.count+ );
Object obj=this;
if(obj instanceof Student) //判断对象属于哪个类
System.out.println(obj.toString()+是Student类对象。);
else if(obj instanceof Person)
System.out.println(obj.toString()+是Person类对象。);
}
}
class Student extends Person //子类Student继承父类Person,且是主类但不是public类
{
static int count=0; //隐藏了父类的count
protected String dept;
protected Student(String n1,int a1,String d1)
{
super(n1,a1); //调用父类的构造方法
dept=d1;
this.count++; //调用子类的静态变量
}
public String toString() //覆盖父类的同名方法
{
return super.toString()+,+dept; //调用父类的同名方法
}
public void display()
{
super.display();
System.out.println(super.count=+super.count);
System.out.println(this.count=+this.count);
}
public static void main(String[] args)
{
Person per=new Person(王涛,23);
per.display();
Student stu=new Student(张三,22,计算机系);
stu.display();
}
}
程序运行结果及其分析:
例8.10 抽象类的应用举例,定义一个形状抽象类Shape,以该抽象类为父类派生出圆形子类Circle和矩形子类Rectangle。
//filename App8_10.java
abstract class Shape //定义形状抽象类Shape
{
protected String name;
public Shape(String xm) //抽象类中的一般方法,本方法是构造方法
{
name=xm;
System.out.print(名称:+name);
}
abstract public double getArea(); //声明抽象方法
abstract public double getlength(); //声明抽象方法
}
class Circle extends Shape //定义继承自Shape的圆形子类Circle
{
private f
文档评论(0)