The second assignment of Java technology--object-oriented Foundation

Source: Internet
Author: User

(a) Study summary 1. What is a construction method? What is an overload of a constructor method? Can the following program be compiled? Why?
public class Test {    public static void main(String args[]) {        Foo obj = new Foo();           }     }class Foo{    int value;    public Foo(int intValue){        value = intValue;    }}

Constructor method: There is no return value, the name is the same as the class name, and the constructor method is called when the object is created (if there is no write constructor, the compiler automatically adds the parameterless constructor method);
Overloading of construction methods: when there are multiple construction methods (no arguments, no arguments, and multiple constructors with different parameters), the overloading of the construction method is used;
The program cannot be compiled. Because the constructor method is defined, the compiler will no longer automatically create the parameterless construction method at compile time, but when the constructor method is called, it wants to invoke the parameterless construction method.
Workaround: Manually create a parameterless construction method.

2. What is the result of running the following procedure? Analyze the reason and how it should be modified.
public class Test {    public static void main(String[] args) {        MyClass[] arr=new MyClass[3];        arr[1].value=100;    }}class MyClass{    public int value=1;}

Result: Run error;
Cause: An array of objects has been created without each element being instantiated separately.
Solution: Arr[1]=new MyClass (); arr[1].value=100;

3. What is the result of running the following procedure? explain why.
public class Test {    public static void main(String[] args) {        Foo obj1 = new Foo();        Foo obj2 = new Foo();        System.out.println(obj1 == obj2);    }}class Foo{    int value = 100;}

Result: false;
Cause: Each time an object is instantiated, the system allocates a memory address to the object, when judged by = = when it is the address, because the address of two objects is different, so they are not equal.

4. What is object-oriented encapsulation and how is encapsulation implemented in Java? Try to illustrate the example.

Encapsulation: encapsulation means that some information is closed, not everyone can see;
Encapsulation implementation: The encapsulation of Java is implemented by declaring properties and methods with the private modifier;

public class Date {    private int year;    public int month;    public int day;}

The year in this date class is encapsulated when you define an object date D=new date (), and for Object D, you can use D.month and, but you cannot use d.year;

5. Read the procedure below to see if you can compile the pass? If not, explain why.


class A{    private int secret = 5;}public class Test{    public static void main(String args[]){        A a = new A();        System.out.println(a.secret++);    }}

The compilation cannot be passed, because the secret is written in front of private, belongs to the proprietary class, can not be called directly in other classes;


public class Test{    int x = 50;    static int y = 200;    public static void method(){        System.out.println(x+y);    }    public static void main(String args[]){        Test.method();    }}

Compilation cannot pass, because X is not static type, so can not be used in static type method;
Workaround: Add static in front of X.

6. Use static variables and construction methods of a class to track the number of objects created by a class. Declare a book class, the data members are numbered, the title, the book Price, and the number of static data member book record number of books. Book numbering starts with 1000, and each object is generated, the number is automatically incremented (implemented using static variables and construction methods). Here is a partial code for the test class code and the book class, which complements the code as a whole.
class book{int bookId;    String BookName;        Double Price;                 The static int x;//declares the static{x=1000;        x=0;//defines static code blocks to initialize static variables} public book (String bookname,double price) {//constructor method This.bookname=bookname;        This.price=price;        This.bookid=x;    x + +;    } public String Getbookname () {return bookname;    } public void Setbookname (String bookname) {this.bookname = BookName;    } public double GetPrice () {return price;    public void Setprice (double price) {this.price = Price;    } public static int Totalbook () {//define method to find the total number of books return x-1000;     } public String ToString () {//Override toString Method Return "book Number:" +bookid+ ", Book Name:" +bookname+ ", Book Price:" +price;                        }}public class test{public static void Main (String args[]) {book[] books = {new book ("C Language Programming", 29.3), New book ("Database Principle", new book ("Java Learning note", 68)};         SYSTEM.OUT.PRINTLN ("Total number of books:" + Book.totalbook ());        for (book book:books) {System.out.println (book.tostring ()); }    }   }
7. What is a singleton design pattern? What characteristics does it have? Design a solar class sun with a single-instance design pattern.

Singleton mode: The core structure contains only one special class that is called a singleton.
Features: Through a single case mode can be guaranteed in the system, the application of the pattern Class A class has only one instance. That is, a class has only one instance of an object.

public class Sun{    private static Sun instance=null;    public static synchronized Sun getInstance(){        if(instance==null){               instance=new Sun();        }        return instance;    }    private Sun(){    }}

8. Understand the Java parameter passing mechanism, read the following program, what is the result of running? explain why.

public class Test {    String str = new String("你好  ");    char[] ch = { ‘w‘,‘o‘,‘l‘,‘l‘,‘d‘ };    public static void main(String args[]) {        Test test = new Test();        test.change(test.str,;        System.out.print(test.str);        System.out.print(;    }    public void change(String str, char ch[]) {        str = "hello";        ch[0] = ‘W‘;    }}

Result: Hello Wolld;
Cause: The char type passes the address, so the result changes, and the string is passed in a new address to store the content to be passed, the content of the new address changes, the original address will not change;

(ii) Experimental summary 1. Complete scoring system with object-oriented thinking

Program Design ideas: Enter the number of contestants, the number of judges, and then enter the player information, so that all the judges to enter the contestants to score, after the score will be sorted, remove the highest score and the lowest score, in the calculation of the average score, the final average score to the player's information, as a contestant's performance;
Question 1: Do not understand the meaning of encapsulation, mistakenly think can not be encapsulated inside any information input;
Solution: Enter the scoring data in the jury class;

2.Email Verification

This question is no problem.

3. Finding substrings

This question is no problem.

4. Statistical documents

Issue 1: For some special situations, consider not comprehensive, such as when a file name contains multiple '. ' ;
Workaround: In this case we need to find the last '. ' And then go to this '. ' The thing behind, with a loop to handle the constant search '. ' and then go '. ' After the content, know that the content does not contain '. ' ;

5. Design of the class

Question 1: Establishing linkages between two classes;
Workaround: Two classes to establish each other's object, and then make the call;
For example: D[i].gete () [C].tostring (); D is the object of the Department class, and Gete () is the function of the employee class;


The second assignment of Java technology--object-oriented Foundation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.