21xrx.com
2025-03-26 17:36:07 Wednesday
文章检索 我的文章 写文章
" + title + "\nAuthor: " + author + "\nPrice: " + price
2023-06-15 10:53:46 深夜i     22     0
Java类的定义 实例化对象 toString方法

Java程序设计基础期末考试题及详解

在Java程序设计基础课程的期末考试中,以下是一些实际的编程考点和难点,这些题目可以让你更好地理解Java语言和编程思维。以下是题目及其详解:

题目一:定义一个类Book,包含书名、作者和价格等属性。实例化两本书并输出它们的信息。

public class Book{
  private String title;
  private String author;
  private double price;
  public Book(String title, String author, double price)
    this.title = title;
    this.author = author;
    this.price = price;
  
  public String getTitle()
    return title;
  
  public String getAuthor()
    return author;
  
  public double getPrice()
    return price;
  
  public String toString()
    return "
  
  public static void main(String[] args){
    Book book1 = new Book("The Great Gatsby", "F. Scott Fitzgerald", 10.99);
    Book book2 = new Book("To Kill a Mockingbird", "Harper Lee", 9.99);
    System.out.println(book1);
    System.out.println(book2);
  }
}

题目二:定义一个接口GeometricObject,包含计算面积和周长的抽象方法。定义一个Rectangle类和一个Circle类实现该接口,并实现两个类中的方法。

public interface GeometricObject{
  public double getArea();
  public double getPerimeter();
}
public class Rectangle implements GeometricObject{
  private double width;
  private double height;
  public Rectangle(double w, double h)
    width = w;
    height = h;
  
  public double getArea(){
    return width * height;
  }
  public double getPerimeter(){
    return 2 * (width + height);
  }
}
public class Circle implements GeometricObject{
  private double radius;
  public Circle(double r)
    radius = r;
  
  public double getArea(){
    return Math.PI * radius * radius;
  }
  public double getPerimeter(){
    return 2 * Math.PI * radius;
  }
}

关键词: 接口的定义、类实现接口、抽象方法、Math类。

题目三:定义一个父类Animal,包含动物的种类和叫声。定义两个子类Dog和Cat,实现它们的叫声属性。同时定义一个接口Swimming,包含游泳的方法,让Dog类和Cat类实现该接口,并实现游泳的方法。

public abstract class Animal{
  private String type;
  public void setType(String t)
    type = t;
  
  public String getType()
    return type;
  
  public abstract String speak();
}
public class Dog extends Animal implements Swimming{
  public Dog(){
    setType("dog");
  }
  public String speak()
    return "woof";
  
  public void swim(){
    System.out.println("Dog is swimming.");
  }
}
public class Cat extends Animal implements Swimming{
  public Cat(){
    setType("cat");
  }
  public String speak()
    return "meow";
  
  public void swim(){
    System.out.println("Cat is swimming.");
  }
}
public interface Swimming{
  public void swim();
}

关键词: 抽象类、继承、接口、重写、多态。

这三道题目都涉及Java中一些常用的面向对象编程方法和语法,例如类的定义、接口的使用、抽象类的实现等等,对于初学者来说是非常有帮助的。在学习Java的过程中,多做练习和考试题可以加深对技能的掌握和理解。

  
  

评论区