I. Key points of study
READ carefully and check the relevant information, master the following content:
Understanding the relationship between object creation and reference
Mastering overloading of construction methods
Mastering the String class
Mastering the design method of class
Master this keyword
Mastering the Static keyword
Understanding reference delivery and mastering basic applications
Mastering the Singleton mode
Understanding Inner Classes
Second, the operation requirements
Publish an essay that mainly includes the following sections:
(a) Learning 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; }}
<1> construction method is to complete the initialization of the object method, generally should be public, the definition of the format is: public class name (parameter table), you can also define a non-parametric construction method, do not define the construction method, the system will automatically generate a non-parametric construction method (note: When the construction method has been written, System is not automatically generated)
The overloading of the <2> constructor method means that the constructor method can have multiple, but the parameter table should be different, and when the parameter table is the same, an error will be given.
<3> No, a constructor with one parameter has been defined, and the system will no longer generate an argument-free constructor, and there is no parameterless constructor in the Foo class, so when the test class calls Foo the parameterless construction method will error
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;}
The results are as follows:
The hint is that there is a problem with a null pointer in line fourth,
Reason:
Elements within an array of objects are not instantiated, and each element within an array of objects is an object that needs to be instantiated separately
Modify:
public class Test { public static void main(String[] args) { MyClass[] arr=new MyClass[3]; for(int i=0;i<arr.length;i++) { arr[i]=new MyClass(); } arr[1].value=100; System.out.println(arr[1].value);//测试语句 }}
Test results:
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;}
Results:
Cause: Because Obj1 and obj2 are referenced addresses, OBJ1 and Obj2 are two objects of different Foo types, and two reference addresses are of course not, so the return is false, The value that should be compared to the value stored in the Obj1 property value and the Obj2 property in value
Modify:
public class Test { public static void main(String[] args) { Foo obj1 = new Foo(); Foo obj2 = new Foo(); System.out.println(obj1.value==obj2.value); }}
Test results:
4. What is object-oriented encapsulation and how is encapsulation implemented in Java? Try to illustrate the example.
<1> once the member variable is defined, it cannot be arbitrarily changed outside the class, the object itself is protected, and the other object is contacted by the object's access method.
<2> to encapsulate the data generally declare the attribute with the Private keyword, and then use the corresponding getter and setter methods of the property to get and set
<3> constructing methods to implement initialization encapsulation of objects
Example:
For example, a bank deposit, whose deposit and balance attributes should be handled by its object itself, cannot be declared with public and should be defined as private so that the data can only be changed when the setter method is initialized and invoked, protecting the data itself
import java.util.Scanner;import java.util.Scanner;class Chuzhi { private int deposit;//存款 private int blance;//余额 public Chuzhi(int deposit) { this.deposit=deposit; this.blance=deposit; } public void setdeposit(int despoit) { this.deposit=deposit; } public int getdeposit() { return deposit; } public void setblance(int draw) { if(draw>blance) System.out.println("false"); blance =blance-draw; } public int getblance() { return blance; }}public class Test { public static void main(String[] args) { Chuzhi a = new Chuzhi(200);//初始存款200 Scanner in = new Scanner(System.in); int draw = in.nextInt(); a.setblance(draw); System.out.println("余额:"+a.getblance()); }}
Results:
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++); }}
No, because the secret property is private and cannot be modified directly outside the class
(2)
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(); }}
No, because static methods are declared statically, where the manipulated variables can only be static variables declared by static
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; Declares a static variable, static int num; Defines static code blocks for static variables initialized with the static {num=1000; }//Construction method public book (String bookname,double price) {this.bookname=bookname; This.price=price; Bookid=num; num++; } 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; }//define method to find the total number of books public static int Totalbook () {return num-1000; }//Override tostring Method public String ToString () {return "number:" +bookid+ "title:" +bookname+ "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 ()); } } }
Operation Result:
7. What is a singleton design pattern? What characteristics does it have? Design a solar class sun with a single-instance design pattern.
Only one instance object is generated for this class during the entire program run
Feature: Only one instance object exists during the entire program run
class Sun { private static Sun sun = new Sun();//定义一个私有成员对象 private Sun() {}//构造方法私有化 public static Sun getsun() { return 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, test.ch); System.out.print(test.str); System.out.print(test.ch); } public void change(String str, char ch[]) { str = "hello"; ch[0] = ‘W‘; }}
Result: Hello Wolld
Reason:
9. Other content that needs to be summarized.
Inner class
<1> when you run an external class, the inner class also generates a. class file
<2> can be accessed directly from an external class, or it can be called in another class
<3> method Inner class is also called local inner class
(ii) Experimental summary
This experiment includes experiment two and experiment 32 times content:
1. Complete the scoring system with object-oriented thinking
Program Design Ideas:
<1> definition of three classes, competitor (contestant Class), score (scoring Class), test (testing Class)
The <2>competitor class is created with a Comepareto interface, the member attributes are numbered, the player's name, the final result of the contestant and their corresponding getter and setter method, the ToString method of returning the basic information of the player, There is also the Comepareto method, the score class defines the number of judges, and the score array is used to store each judge scored points, methods have their corresponding setter and getter method, the method of inputting scores, averaging, seeking maximum value, to find the minimum value of the method, The parameter of the input score method is a double type of data + subscript. Using a loop to find the maximum and minimum values, in the average call, the sum of the points given by all judges, minus Max and Min, divided by (the total number of judges-2); The test class first lets the user enter the number of contestants and the number of judges, and then creates an array of objects based on this to input data and call
Problem: null pointer exception problem
Cause: An array of objects is not instantiated
Solution: Instantiate object one by one in an array of objects in a loop
2.Email Verification
Program Design Ideas:
<1> Let the user enter the email address first
<2> Use the Boolean method to determine if it is valid and returns True
<3> Judgment Method:
Splits a string string into a character array using the Tochararrays () method to determine if the first is @, or False if it is returned
defines a two Boolean variable whose initial value is false, creating a for loop with the loop body: If the character array element i is ". , the first variable is set to True, and if "@", the second is set to true, judging if the first variable is true and the second is false, then false if the first variable is true and the second variable is true, the loop is jumped out
Then @ does not exist, if temp2=0, it is possible '. ' Does not exist, or '. ' Before @, this idea was wrong
Cause: If the email address is[email protected]@qq. com, the program will error
Solution: Change to the current method
Question <2>: "= =" is used when comparing the last element of a character array with a point split to meet the requirements
Cause: Character comparisons cannot be "= =", so the comparison is a reference
Solution: Change to Equals method
3. Finding substrings
Program Design Ideas:
<1> gets the original string, replacing all substrings in the original string with an empty string
<2> calculates the length of the original string and the length of the string after the change and the length of the substring
<3> finally returns (the length of the original string-the length of the string after the change)/substring length
Problem: None
4. Statistical documents
Program Design Ideas:
<1> Let the user enter the file string themselves, press "," split into a character array
The upper and lower methods are provided in <2>java for case conversion, so the first bit of each element in the character array is truncated and the upper method is capitalized, plus all the characters from the first position are assigned to this element
<3> will be pressed "," after the file name is split, then press "." Splits, depositing the last element into the kind array
<4> defines a double array as an array of kind numbers, using the Fill method of the arrays class to set each bit to one, a two-layer loop, an outer loop to set the number of each type, and a memory loop to compare each, when the type used to compare is not NULL. When the same is found, its corresponding number is added one, and the same kind of class name is set to NULL
Problem: First run discovery compares only the first type, others are null
Reason: The Equals method was used wrong
Solution: Change to Equalsignorecase method
5. Design of the class
Program Design Ideas:
<1> set Date class, Department category, employee class, test class
The <2> date class defines 3 int variables year, month,day, define assignments directly in the constructor method, and sets a ToString method to return to the date format
<3> worker class define number, name, gender, work Department 4 string variables, also define two date class variables, all empty, birthday and work time, constructor method directly assigned value, and write a ToString method to return the basic information of workers
Division number, department name two string variables and a variable manager for a worker class in the <4> Department category
<5> test class defines an array of employee class objects, and directly initializes, defines an array of objects for the Department class, and the manager controls the output format for an object in the employee array.
Problem: Object array does not know how to initialize
Solution: By checking the book, each object in an object array needs to be instantiated separately
Problem: The object array does not know how to initialize the date class
Solution: Set a Date Class anonymous object
(c) Code hosting (be sure to link to your project)
The second job of JAVA technology