Java 定义一个抽象类—水果,其中包括getWeight()方法,创建若干水果对象存放在一个水果类型的数组中,输出数组中所有水果的类型、重量。

Java 定义一个抽象类—水果

其中包括getWeight()方法,编写程序分别创建苹果、桃子、橘子3个类,创建若干水果对象存放在一个水果类型的数组中,输出数组中所有水果的类型、重量。

抽象类Fruits:

public abstract class Fruits {
 private double weight;
 
public double getWeight() {
  return weight;      
 }
 public void setWeight(double weight) {
  this.weight = weight;
 }
public abstract double weight();
}

标准类:

public class Apple extends Fruits {

@Override
 public double weight() {
  // TODO Auto-generated method stub
  //K.kuimeng
  return getWeight();
 }
 @Override
 public String toString() {
  return "苹果的重量:" + weight();
 }
 }

class Peach extends Fruits{
@Override
 public double weight() {
  // TODO Auto-generated method stub
  //K.kuimeng
  return getWeight();
 }
 @Override
 public String toString() {
  return "桃子的重量:" + weight();
 } 
 }

class Orange extends Fruits{
@Override
 public double weight() {
  // TODO Auto-generated method stub
  return getWeight();
 }
 @Override    //K.kuimeng
 public String toString() {
  return "橘子的重量:" + weight();
 }
 }

测试类:

import java.util.Arrays;


public class FruitsTest {
Fruits[] a;    //K.kuimeng
public static void main(String[] args) {
  // TODO Auto-generated method stub
  Apple apple=new Apple();
  apple.setWeight(6);

  Peach peach=new Peach();
  peach.setWeight(5);

  Orange orange=new Orange();
  orange.setWeight(7);   //K.kuimeng

  FruitsTest s1=new FruitsTest();
  s1.a=new Fruits[] {apple,peach,orange};
  System.out.println(Arrays.toString(s1.a));
  }}

运行结果:

[苹果的重量:6.0, 桃子的重量:5.0, 橘子的重量:7.0]

喜欢博主代码的朋友记得点赞关注博主哟~

你可能感兴趣的:(java,Java小白必学题)