龙空技术网

JAVA实验(10.18)

博学沙滩55Q 33

前言:

现在同学们对“java实验报告实验总结万能模板”大概比较关切,兄弟们都需要了解一些“java实验报告实验总结万能模板”的相关内容。那么小编也在网摘上网罗了一些有关“java实验报告实验总结万能模板””的相关资讯,希望兄弟们能喜欢,同学们一起来学习一下吧!

1、设计一个图形类Shape,其中包含一个抽象方法calculateArea()用于计算图形面积。图形类有两个子类:圆形类Circle和矩形类Rectangle,分别实现calculateArea()方法来计算圆形和矩形的面积。在主程序中,创建一个Shape类型的数组,数组中放置不同形状的图形,并通过循环遍历数组,计算并打印出每个图形的面积。

package com.example.practice;

abstract class Shape{

public abstract double calculateArea();

}

class Circle extends Shape{

private double radius;

private double a=3.14;

public Circle(double radius) {

this.radius = radius;

}

public double calculateArea() {

return a* radius * radius;

}

}

class Rectangle extends Shape{

private double x;

private double y;

public Rectangle(double x, double y){

this.x = x;

this.y = y;

}

public double calculateArea(){

return x*y;

}

}

public class Practice06 {

public static void main(String[] args){

Shape[] s = new Shape[2];

s[0] = new Circle(2);

s[1] = new Rectangle(2,3);

for(Shape shape : s){

shape.calculateArea();

System.out.println("Area:"+shape.calculateArea());

}

}

运行结果

2、设计一个动物类Animal,包含抽象方法makeSound()和具体方法move()。动物类有两个子类:狗类Dog和猫类Cat,分别实现makeSound()方法来发出不同的声音。在主程序中,创建一个Animal类型的数组,数组中放置不同的动物,并通过循环遍历数组,让每个动物发出声音和移动。

package com.example.practice;

abstract class Animal{

abstract void makeSound();

void move(){};

}

class Dog extends Animal{

void makeSound(){

System.out.println("汪汪汪");

}

public void move(){

System.out.println("Animal is moving.");

}

}

class Cat extends Animal{

void makeSound(){

System.out.println("喵喵喵");

}

public void move(){

System.out.println("Animal is moving.");

}

}

public class Practice05 {

public static void main(String[] args){

Animal[] animals = new Animal[2];

animals[0] = new Dog();

animals[1] = new Cat();

for(Animal animal : animals){

animal.makeSound();

animal.move();

System.out.println("===================");

}

}

}

运行结果

标签: #java实验报告实验总结万能模板