"JAVA third homework"

(1) Learning summary

1. Read the following program, can the analysis be compiled and passed? If not, explain why. How should it be modified? What is the result of running the program? Why does the constructor of the subclass have to call the constructor of the parent class before it can run? Can it be reversed?

class Grandparent {
    public Grandparent() {
        System.out.println("GrandParent Created.");
    }
    public Grandparent(String string) {
        System.out.println("GrandParent Created.String:" + string);
    }
}
class Parent extends Grandparent {
    public Parent() {        
        System.out.println("Parent Created");
        super("Hello.Grandparent.");
    }
}
class Child extends Parent {
    public Child() {
        System.out.println("Child Created");
    }
}
public class Test{
    public static void main(String args[]) {
        Child c = new Child();
    }
}

Does not compile, reason: The constructor call must be the first statement in the constructor. Put the statement super("Hello.Grandparent.")" in the first sentence of the constructor of the subclass Parent. The
constructor (constructor) is a special method. It is mainly used to initialize the object when it is created, that is, the object Member variables are assigned initial values ​​and are always used with the new operator in the statement to create an object. A special class can have multiple constructors, which can be distinguished according to the number of parameters or the type of parameters, that is, constructors The function of the constructor is mainly used to define the initialization state when the object of the class is created. To
construct an object, call its constructor first to initialize its member functions and member variables.
The subclass has the parent's member variables and members If the method is not called, the member variables and member methods inherited from the parent class will not be properly initialized.
This is also the reason why the parent class cannot be called in reverse, because the parent class does not know that the child class has magical variables and this way The subclass also cannot get the initialized parent class variable, which causes the program to run incorrectly.

2. Read the program below, analyze what errors exist in the program, explain the reasons, and how to correct them? What is the result of running the correct program?

class Animal{
  void shout(){
      System.out.println("动物叫!");
  }
}
class Dog extends Animal{
      public void shout(){  
          System.out.println("汪汪......!");  
     }
      public void sleep() {
       System.out.println("狗狗睡觉......");
      } 
}
public class Test{
    public static void main(String args[]) {
        Animal animal = new Dog(); 
        animal.shout();
        animal.sleep();
        Dog dog = animal;
        dog.sleep(); 
        Animal animal2 = new Animal();
        dog = (Dog)animal2;
        dog.shout();
    }
}

No method sleep() defined for type Animal
Type mismatch: cannot convert from Animal to Dog
Modified program:

class Animal{
  void shout(){
    System.out.println("动物叫!");
}
void sleep(){
     System.out.println();
}
}
class Dog extends Animal{
     public void shout(){  
          System.out.println("汪汪......!");  
    }
    public void sleep() {
    System.out.println("狗狗睡觉......");
    } 
}
public class Test{
    public static void main(String args[]) {
        Animal animal = new Dog(); 
        animal.shout();
        animal.sleep();
        Dog dog = (Dog)animal;
        dog.sleep(); 
        Animal animal2 = new Dog();
        dog = (Dog)animal2;
        dog.shout();
    }
}

3. Run the following program

class Person { 
   private String name ; 
   private int age ; 
   public Person(String name,int age){ 
         this.name = name ; 
         this.age = age ; 
   } 
}
public class Test{  
      public static void main(String args[]){ 
             Person per = new Person("张三",20) ; 
             System.out.println(per);
             System.out.println(per.toString()) ; 
  } 
}

(1) The running result of the program is as follows, what is the problem?

Person@166afb3
Person@166afb3

The String tostring() method is not called.

(2) Then, what is the result of running the program? Use eclipse to open the source code of the println(per) method and see which methods are called in this method. Can you explain the running result of this example?

public void println(Object x) {
    String s = String.valueOf(x);
    synchronized (this) {
        print(s);
        newLine();
    }
}

(3) Add the following method
java public String toString(){ return "姓名:" + this.name + ",年龄:" + this.age ; }operation results to the Person class:
Name: Zhang San, Age: 20
Name: Zhang San, Age: 20
Explain that the subclass Person class repeats the toString() method in the Object class

4. Car rental companies, there are three types of taxis: passenger cars, trucks and pickups. In addition to the three basic attributes of serial number, name and rental, each car has a passenger capacity, a truck has a cargo capacity, and a pickup has both. Has passenger and cargo capacity. Analyze the above problems with the idea of ​​object-oriented programming, express them as suitable classes, abstract classes or interfaces, and illustrate the design ideas. Now to create a rental car list, how do I create it?

Design ideas:

(1) Define an abstract class with three attributes: number, name, and rent;

(2) Define two interfaces: cargo capacity and passenger capacity;

(3) Define three subclasses to inherit the abstract class, the passenger car class implements the passenger capacity interface, the train class implements the cargo capacity interface, and the pickup class implements the passenger capacity and cargo capacity interfaces.

5. Read the following program, analyze whether the code can be compiled and passed, if not, explain the reason and make corrections. If yes, list the results of the run

interface Animal{    
        void breathe();
        void run();
        void eat();
    }
    class Dog implements Animal{
        public void breathe(){
            System.out.println("I'm breathing");
        }
        void eat(){
            System.out.println("I'm eating");
        }
    }
    public class Test{
        public static void main(String[] args){
            Dog dog = new Dog();
            dog.breathe();
            dog.eat();
        }
    }

No: methods in interfaces are public abstract by default, so when subclasses implement abstract methods, they should be modified with public

(2) Experiment summary

Experiment content:
Define an employee class with attributes of name, age, and gender, as well as a construction method and a data display method. Define the management class, inherit the employee class, and have its own attribute title and annual salary. Define the employee class, inherit the employee class, and have its own attributes of the department and monthly salary. Define a test class to test.

2. Complete the class design according to the following requirements

(1) Design a flat graphic abstract class (providing methods for finding the perimeter and area of ​​objects of this type) and a three-dimensional graphic abstract class (providing methods for finding the surface area and volume of objects of this type)

(2) Design spheres, cylinders, cones, rectangles, triangles, and circles, respectively inheriting the abstract classes of plane graphics and abstract three-dimensional graphics.

(3) Create a test class for testing. Draw a class diagram.

3. Refer to the class diagram, reconstruct the following examples, analyze and understand the meaning and purpose of polymorphism

(1) A zookeeper Xiao Li needs to feed one lion, five monkeys and ten pigeons that he is responsible for raising every day. Please use a program to simulate his feeding process.

Analyze what's wrong with this way of programming.

(2) The first reconstruction, the introduction of inheritance, the use of abstract classes and object polymorphism to reconstruct the program, the Animal class adopts the abstract class, and the methods in the Feeder class are merged

Whether the analysis program can be further optimized

(3) The second refactoring, modify the feedAnimals method so that it receives an array of Animals

(3) Code hosting (be sure to link to your project) https://gitee.com/hebau_java_cs16/Java_CS01-wyn/tree/master/ex03

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324645848&siteId=291194637