一、类和对象
1.定义一个类Demo,其中定义一个求两个数据和的方法,定义一个测试了Test,进行测试。
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,进行测试。
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()方法,以及一个显示所有成员信息的方法。并测试。
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,提供基本的加减乘除功能,然后进行测试。
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.定义一类圆,求圆的周长和面积
class Circle{
double r;
public double getPermeter(){
return 3.14*r*2;
}
public double getArea(){
return 3.14*r*r;
}
}