//1

day13 面向对象练习-LMLPHP

 public class Area_interface
{
public static void main(String[] args)
{
Rect r = new Rect(15, 12);
Circle c = new Circle(8);
System.out.println(r.getArea());
System.out.println(c.getArea());
}
} interface Areable{
double getArea();
} class NotValueException extends RuntimeException{
NotValueException(String message){
super(message);
}
} // 矩形
class Rect implements Areable{
private int length,width;
public Rect(int length,int width) {
if (length <= 0 || width <= 0){
throw new NotValueException("数值非法!");
}
this.length = length;
this.width = width;
}
public double getArea()
{
return length*width;
}
} // 圆形
class Circle implements Areable{
private int radius;
private static final double PI = 3.14;
public Circle(int radius) {
this.radius = radius;
}
public double getArea()
{
return PI*radius*radius;
}
}

//2

day13 面向对象练习-LMLPHP

 public int search_char(char[] chs, char key)
{
if(chs==null){
throw new IllegalArgumentException("数组为空");
}
for(int x = 0;x < chs.length;x++){
if(key==chs[x]){
return x;
}
}
return -1;
}

//3

day13 面向对象练习-LMLPHP

 //first method
int max = 0; //初始化为数组中的任意一个角标
for(int x = 1; x < cir.length; x++){
if(cir[x].radius > cir[max].radius){
max = x;
}
}
return cir[max].radius; //second
double max = cir[0].radius; //初始化为数组任意一个元素的半径
for(int x = 1; x < cir.length; x++){
if(cir[x].radius >max){
max = cir[x].radius;
}
}
return max;

//4

day13 面向对象练习-LMLPHP

 class Person{
private int age;
private String name;
public Person(int age, String name) {
super();
this.age = age;
this.name = name;
} public void say()
{
System.out.println(name+" "+age);
}
//下面两个都是通过右键搞定的
//get和set方法
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
//hashcode和equals方法
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}

equals方法通过eclipse自动生成

day13 面向对象练习-LMLPHP

//5

day13 面向对象练习-LMLPHP

 public boolean equals(Object other){
if( !(other instanceof Circle) ){
throw new ClassCastException(other.getClass().getName+"类型错误");
}
Circle c = (Circle)other;
return c.radius==this.radius;
}
05-12 02:43