BD-11-day07练习-类和对象

类就像一个箱子,里面装有用来描述实际事物的状态和行为的语句。

对象是类的一个实例化,也就是一个大的类型中,其中具体的某个东西,比如:人类是个类,实例化就是具体到一个人,包含她叫什么名字,具有什么样的行为,可以执行什么样的动作。

一个java文件只能有一个public修饰的类,且类名和文件名一致,

如果没有public类, class 类的名字可以和文件名不一样,但是好习惯还是写相同的名字。

简------>繁

1.小美在朝阳公园溜旺财【注:旺财是狗】

(这是初学者的写方式哈,勿喷,真正写项目或是写比较量大的代码时,成员变量还是用修饰符比较好,用private保护,防止外类随意修改或直接访问)

public class Test {
    public static void main(String[] args){
        Person person = new Person("小美");
        Dog dog = new Dog("wangcai");
        person.running(dog);

    }
}


class Person {
    String name;
    Person(String name){
        this.name = name;
    }
    void running(Dog dog){
        System.out.println(this.name+"在朝阳公园"+"溜"+dog.name);
        dog.walk();
    }
}

class Dog{
    String name;
    Dog(String name){
        this.name=name;
    }
    void walk(){
        System.out.println("主人陪我出来溜哒会.....");
    }
}

2.定义一“圆”(Circle)类,圆心为“点”Point类,构造一圆,求圆的周长和面积,并判断某点与圆的关系

public class CTest {
    public static void main(String[] args){
        Point p0 = new Point(6,8);
        Point p1 = new Point(2,4);
        double len,detax,detay;
        Circle circle = new Circle(p0,4);
        System.out.println("primeter:"+circle.primeter());
        System.out.println("area is:"+circle.area());
        detax = Math.pow(p0.x-p1.x,2);//两x相减的平方
        detay = Math.pow(p0.y-p1.y,2);//y相减的平方
        len = Math.sqrt(detax+detay);//两点之间的距离
        if ( circle.radius == len ) {
            System.out.println("p1在圆上");
        }else if (circle.radius > len ){
            System.out.println("P1在圆内");
        }else {
            System.out.println("P1在圆外");
        }
     
    }
}

class Point{
    double x;
    double y;
    Point(int x,int y){
        this.x=x;
        this.y=y;
    }

}
class Circle{
    Point p0; //成员变量是个对象
    double radius;
    Circle(Point p0,double radius){
        this.p0=p0;
        this.radius=radius;
    }
    double primeter(){
        return 2*Math.PI*this.radius;
    }
    double area(){
        return Math.PI*this.radius*this.radius;
    }
}

感觉这样写测试类计算两个点之间的距离,好像跟Circle没有关系。优化一下,把判断的是否在圆内封装在Circle中。

当类中的成员变量是另一个类时,怎么在测试类中访问类中类的成员变量呢?

在测试类中可以用circle.p0.x 访问对象中的类的成员变量。

Number类中的equals()方法:

public boolean equals(Object o)

如果 Number 对象不为 Null,且与方法的参数类型数值都相等返回 True,否则返回 False。(是否指向同一对象)

猜你喜欢

转载自blog.csdn.net/weixin_42474930/article/details/81253400
今日推荐