Java Head Song 9-4 Application of Abstract Classes

Level 1: multiple choice questions

Task Description

Tasks for this level: Complete multiple-choice questions about abstract classes and their applications.

In order to complete this task, you need to master: 1. Abstract classes and abstract methods, 2. Issues to pay attention to in inheritance: such as calling constructors, method overriding, using objects of the parent class to reference objects of the subclass, parent class Inheritance issues of private members, use of final modifier and static modifier, etc.

Abstract class

(1) An abstract class is an abstraction of multiple similar classes; (2) An abstract class is defined with abstract; an abstract method is defined with abstract and has no function body; there may be no abstract method in an abstract class, but the class containing the abstract method must be declared is an abstract class. (3) The specific implementation of the abstract method must be given in the subclass based on the abstract class (different subclasses have different implementation methods – polymorphism) (4) The abstract class cannot be instantiated (that is, the object of the abstract class cannot be created, Because abstract methods cannot be executed), you can declare objects of abstract classes and use them to reference objects of different subclasses, thereby achieving: the same statement (operation), realizing different functions – polymorphism

Level 2: Programming Implementation: Animal Sound Simulator

Task description

The task of this level: Design an animal generation simulator to simulate the sounds of different animals. For example, a lion roars, a tiger roars, a dog roars, a cat meows… Define the abstract class Animal, which contains two abstract methods: get the animal category getAnimalClass(), and the animal’s name shout(); then define the dog class Dog and cat class Cat based on the abstract class Animal, and use the getAnimalClass() method to return different animal categories (such as Cats, dogs), use the shout() method to output different sounds. Finally, write the AnimalShoutTest class test, such as outputting “the dog’s bark is: woof woof”.

Related knowledge

In order to complete this task, you need to master: 1. The definition of abstract classes, 2. Defining subclasses with abstract classes, 3. Method rewriting, 4. The definition and use of objects.

Reference Case

//Define abstract class public abstract class Shape { //Define 2 abstract methods public abstract double GetArea();
public abstract double GetCircum(); //Define common methods public void print() { System.out.println(“Perimeter:” + GetCircum() + “Area:” + GetArea()); } } //Define the Circle class based on the Shape abstract class public class Circle extends Shape{ public double radius; //Add new array member: radius //Constructor public Circle(double r){ this.radius=r; } //Override inheritance method (concrete implementation of abstract method) public double GetArea(){ return 3.14radiusradius; } public double GetCircum(){ return 23.14radius; } } // Define the Rectangle class based on the abstract class Shape public class Rectangle extends Shape { //Add 2 new data members: length and width public double width; public double length; //Constructor public Rectangle(double wid,double len){ this.width =wid; this.length=len; } //Concrete implementation of abstract method public double GetArea(){ return widthlength; } public double GetCircum(){ return 2(width + length); } } //Test class Test public class Test { public static void main(String[] args){ Circle cir=new Circle(5); //Create a circle object cir Rectangle rec=new Rectangle(2,4); // Create a rectangular object rec cir.print(); //Output circular information rec.print(); //Output rectangular information Shape sh; //Declare abstract class objects, but cannot create sh=cir; / /Use sh to reference cir sh.print(); //Output circular information sh=rec; //Use sh to reference rec sh.print(); //Output rectangular information} }

Programming Requirements

Follow the prompts and add code at the specified location in the editor on the right.

Test Instructions

The platform will test the code you write:

Test input: Expected output: Cat’s meow: meow Dog’s meow: woof woof

//Animal occurrence simulator. Please fill in the code in [] below.
public class AnimalShoutTest {
 
public static void main(String[] args) {
//Create object cat of Cat class and object dog of Dogz class
Cat cat=new Cat();
        Dog dog=new Dog();
\t\t 
System.out.print(cat.getAnimalClass() + "Call:");
cat.shout();
System.out.print(dog.getAnimalClass() + "Call:");
dog.shout();
}
}
//Define the abstract class Animal, including two abstract methods getAnimalClass() and shout()
abstract class Animal{
public abstract String getAnimalClass();
public abstract void shout();
}
//Define subclass Cat based on Animal class
class Cat extends Animal{
public String getAnimalClass() {
return("cat");
}
\t
public void shout(){
System.out.println("Meow Meow");
}
}
//Define subclass Dog based on Animal class
class Dog extends Animal{
public String getAnimalClass() {
return("dog");
}
\t
public void shout(){
System.out.println("woof");
}
}

Level 3: Animal Sound Simulator-Improved Version

Task description

Tasks in this level: Same as level 2, except that in the main() method, the Animal object is used to reference the methods in the cat and dog objects. Specific requirements: Design an animal generation simulator to simulate the sounds of different animals. For example, a lion roars, a tiger roars, a dog roars, a cat meows… Define the abstract class Animal, which contains two abstract methods: get the animal category getAnimalClass(), and the animal’s name shout(); then define the dog class Dog and cat class Cat based on the abstract class Animal, and use the getAnimalClass() method to return different animal categories (such as Cats, dogs), use the shout() method to output different sounds (such as meow, woof). Finally, write the AnimalShoutTest class test, output: cat’s cry: meow, dog’s cry: woof.

Among them, in the AnimalShoutTest class, use the speak(Animal animal){} method to output the animal’s cry, and call the speak() method in the main() method to output the sounds of the cat and dog objects respectively.

Related knowledge

In order to complete this task, you need to master: 1. The definition of abstract classes, 2. Defining subclasses with abstract classes, 3. Method rewriting, 4. Definition and use of objects, 5. Using objects of the parent class to reference subclasses Overridden methods in objects

Use the object of the parent class to reference the overridden or inherited method of the object of the subclass

For example, in the following program, Shape is an abstract class, Circle and Rectangle are subclasses, both of which override abstract methods //Define abstract class public abstract class Shape { //Define 2 abstract methods public abstract double GetArea();
public abstract double GetCircum(); //Define common methods public void print() { System.out.println(“Perimeter:” + GetCircum() + “Area:” + GetArea()); } } //Define the Circle class based on the Shape abstract class public class Circle extends Shape{ public double radius; //Add new array member: radius //Constructor public Circle(double r){ this.radius=r; } //Override inheritance method (concrete implementation of abstract method) public double GetArea(){ return 3.14radiusradius; } public double GetCircum(){ return 23.14radius; } public void print (){ System.out.print(“round”); super.print(); } } //Define the Rectangle class based on the abstract class Shape public class Rectangle extends Shape { //Add 2 new data members: long , public double width; public double length; //Constructor public Rectangle(double wid,double len){ this.width=wid; this.length=len; } //Concrete implementation of abstract method public double GetArea(){ return widthlength; } public double GetCircum(){ return 2(width + length); } public void print(){ System.out.print(“rectangular”); super.print (); } } //Test class Test public class Test { public static void main(String[] args){ //Create a circle object cir Circle cir=new Circle(5); //Create a rectangular object rec Rectangle rec =new Rectangle(2,4);
cir.print(); //Output circular information rec.print(); //Output rectangular information Shape sh; //Declare abstract class objects, but cannot create sh=cir; //Use sh to reference cir sh.print(); //Output circular information sh=rec; //Use sh to reference rec sh.print(); //Output rectangular information} }

Question: In the program statements used to output circle information and rectangle information using sh, except for the object name, everything else is exactly the same. That is, duplicate code occurs.

Optimization: In the test class, use a method to output graphics information. public static void show(Shape sh) { sh.print(); }

Then the last 5 lines of code in the main() method can be optimized as: show(cir);
show(rec); Optimization goal: Use one statement to operate multiple subclass objects, and use the subclass objects as parameters.

Programming requirements

Follow the prompts and add code in the editor on the right.

Test instructions

The platform will test the code you write:

Test input: Expected output: Cat’s meow: meow Dog’s meow: woof woof

 //Animal generation simulator. Please add code at [] below.
public class AnimalShoutTest2 {
public static void main(String[] args) {
Cat cat = new Cat();
Dog dog = new Dog();
// speak(cat);
// speak(dog);
        cat.speak();
        dog.speak();
}
//Define static method speak()
}
//Define abstract class Animal
abstract class Animal{
public abstract String getAnimalClass();
    public abstract void speak();
}
//Based on the Animal class, define the cat class Cat and rewrite two abstract methods
class Cat extends Animal{
public String getAnimalClass(){
        return ("cat");
    }
    public void speak(){
        System.out.println("Cat's meow: meow");
    }
}
//Based on the Animal class, define the dog class Dog and rewrite two abstract methods
class Dog extends Animal{
public String getAnimalClass(){
        return ("dog");
    }
    public void speak(){
        System.out.println("Dog's bark: woof woof");
    }
\t
}

Level 4: Correction of wrong questions

Task description

Tasks for this level: About the role of final. Modify the given program so that the program can run smoothly and the results are as follows: speedlimit=120 running safely with 100kmph running safely with 100kmph

Related knowledge

In order to complete this task, you need to master: 1. Abstract classes and abstract methods, 2. The usage of final.

final

1. Modify a class, then the class is the final class, that is, it cannot be used as a parent class to define a new subclass; 2. Modify a method, then the method is the final method and cannot be overridden; 3. Modify a member variable, then the method Members are constants and their values cannot be changed.

Programming requirements

Follow the prompts and modify the source program in the editor on the right according to the compiled error prompts.

Test instructions

The platform will test the code you write:

Test input: Expected output: speedlimit=120 running safely with 100kmph running safely with 100kmph

/* Please modify the source program between Begin and end below.
  The value of a final variable cannot be modified
  final method, cannot be overridden
  Final classes cannot be defined
*/
public class finalTest {
    public static void main(String args[]) {
        Bike1 obj = new Bike1();
        obj.run();
 
        Honda honda = new Honda();
        honda.run();
 
        Yamaha yamaha = new Yamaha();
        yamaha.run();
    }
}
 
    /********** Begin *********/
    class Bike1 {
     int speedlimit = 90;
 
    void run() {
        speedlimit = 120;
        System.out.println("speedlimit=120");
    }
 
}
 
class Bike2 {
     void run() {
        System.out.println("running");
    }
}
 
class Honda extends Bike2 {
    void run() {
        System.out.println("running safely with 100kmph");
    }
 
}
 
 class Bike3 {
}
 
class Yamaha extends Bike3 {
    void run() {
        System.out.println("running safely with 100kmph");
    }
 
}