前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >面向对象练习题

面向对象练习题

作者头像
一缕82年的清风
发布2021-12-06 11:09:49
3300
发布2021-12-06 11:09:49
举报
文章被收录于专栏:lsqingfeng

一、类和对象

1.定义一个类Demo,其中定义一个求两个数据和的方法,定义一个测试了Test,进行测试。

代码语言:javascript
复制
class Demo{
    int a;
    int b;
    public Demo(int a,int b){
        this.a = a;
        this.b = b;
    }
    public int add(){
        return a+b;
    }
}

class Test{
    public static void main(String[] args){

        Demo d = new Demo(1,3);//将1和3 赋值给成员变量
        int result = d.add();//调用add,计算成员变量的和
        System.out.println(result);//4
    }
    
}

2.定义一个长方形类,定义 求周长和面积的方法,然后定义一个测试了Test2,进行测试。

代码语言:javascript
复制
class Rectangle{
    int length;//长
    int width;//宽
    public int getZhouChang(){//求周长
        return 2*(length+width);
    }
    public int getArea(){
        return length*width;
    }
    public Rectangle(){}
    public Rectangle(int length,int width){
           this.length = length;
           this.width = width;
    }
}

class Test2{
    public static void main(String[] args){
        Rectangle r = new Rectangle(12,3);//创建一个长12,宽3的长方形
        int zhouChang = r.getZhouChang();
        int area = r.getArea();
        System.out.println(zhouChang);
        System.out.println(area);
    }

}

3.定义一个员工类,自己分析出几个成员,然后给出成员变量,构造方法, getXxx()/setXxx()方法,以及一个显示所有成员信息的方法。并测试。

代码语言:javascript
复制
class Employee{
    private String name;
    private int age;
    private int id;
    public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
    public Employee(String name, int age, int id) {
		super();
		this.name = name;
		this.age = age;
		this.id = id;
	}
    public Employee(){}
    
}

class Test3{
    public static void main(String[] args){
        Employee e1 = new Employee("张三",12,1);
        Employee e2 = new Employee();
        e2.setName("李四");
        e2.setAge(19);
        e2.setId(2);
        
    }
}

4.定义一个类MyMath,提供基本的加减乘除功能,然后进行测试。

代码语言:javascript
复制
class MyMath{
    int a;
    int b;
    public MyMath(int a,int b){
        this.a = a;
        this.b = b;
    }
    public int add(){
        return a+b;
    }
    public int sub(){
        return a-b;
    }
    public int mul(){
        return a*b;
    }
    public int div(){
        return a/b;
    }

}

5.定义一类圆,求圆的周长和面积

代码语言:javascript
复制
class Circle{
    double r;
    public double getPermeter(){
        return 3.14*r*2;
    }
    public double getArea(){
        return 3.14*r*r;
    }


}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018/11/03 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档