纯作业代码——Java实现接口、继承
2009-10-16 19:33
716 查看
//该代码实现结果为如果设定的长和宽相等则实例化正方形(Square)的类,否则实例化矩形类。 interface rect{ public double area(); public void getWidth(double Width); public void getHeight(double Height); } class Rectangle1 implements rect{ double _width,_height; public void getWidth(double Width){ _width=Width; } public void getHeight(double Height){ _height=Height; } public double area(){ return(_width*_height); } } class Square extends Rectangle1{ public double area(){ return(_width*_width); } } public class test1{ //At here ,I use the super class to define rect1. static Rectangle1 rect1; //set the value of width and height,then judge the shape,and Print them public static void SetValue(double width ,double height){ if(width==height) rect1=new Square(); else rect1=new Rectangle1(); rect1.getWidth(width); System.out.println("The Width value is :"+width+"."); rect1.getHeight(height); System.out.println("The Height value is :"+height+"."); if(width==height) System.out.println("The shape is Square!"); else System.out.println("The shape is Rectangle!"); } //get the result,and print it public static void CalcIt(){ System.out.println("The result is :"+rect1.area()+"."); } public static void main(String args[]){ //set the width and height SetValue(10,10); CalcIt(); System.out.println('/n'); //set the width and height SetValue(10,50); CalcIt(); } }
这是教材上的一道题。首先写了一个计算矩形的类,然后再让写一个正方形的类来继承矩形类。并且要求重写父类中的至少一个方法。
于是有了这段代码。
各位尽管点评。
ps:高等教育出版社的书,“不'错'~~~~(>_<)~~~~ ”
相关文章推荐
- Java 实现多线程的3种方法:继承Thread类;实现Runnable接口;实现Callable接口。具体代码实现实例
- Java中继承thread类与实现Runnable接口区别的简要的分析
- java之实现Cloneable接口的详解,克隆一个对象--对应有浅克隆和深克隆,概念结合代码深入理解
- 多线程——Java中继承Thread类与实现Runnable接口的区别
- [转] Java中继承thread类与实现Runnable接口的区别
- Java 继承Thread类和实现Runnable接口的区别
- Java开发工具_Eclipse中继承抽象类或者实现接口的简化
- java创建多线程的两种方法(继承Thread类/实现Runnable接口)
- 良好的代码规范(子类继承父类后如果实现额外的接口时应把父类实现的接口也在implements语句后写出来)
- java 接口 实现和继承关系
- Java 多线程实现接口Runnable和继承Thread区别
- JAVA中如何用接口实现多继承和多态 (非常好)
- 《Java编程思想》之接口(Java中实现多重继承?!)
- java实现接口与继承类的区别
- java继承类与实现接口
- java 学习 私有类实现接口 ,一个类继承来的方法和接口实现方法重复第八天
- JAVA多线程实现方式主要有三种:继承Thread类、实现Runnable接口、使用ExecutorService、Callable、Future实现有返回结果的多线程。其中前两种方式线程执行完后都没
- Java通过接口实现匿名类的实例代码
- 【Java面试题】60 接口是否可继承接口? 抽象类是否可实现(implements)接口? 抽象类是否可继承具体类(concrete class)? 抽象类中是否可以有静态的main方法?
- java两种启动线程方法根本不同,Thread继承和实现Runable接口