java-day08 pm-Summary, test

Source: Internet
Author: User
Tags define abstract

Inheritance summary: class {public static void main (string[] args) {System.out.println ("Hello world!");}} class fu{private int num = 9;public void Show1 () {}public void setnum (int num) {this.num = num;} Fu () {}}class Zi extends fu{//int num = 4;void Show () {int num = 7; System.out.println (Super.num);}} Zi z = new Zi (); Z.setnum (4); Inheritance: Features: 1, which improves the reusability of code. 2, the relationship between classes and classes is the precondition of polymorphism.

Inheritance in Java.

1. Java only supports single inheritance. Multiple inheritance is not supported. Why is it? Answer: The subclass object is not sure which one to execute because the same method is assumed when multiple parent classes are inherited. 2. Java also supports multilayer inheritance. A-->b--->c was able to form a succession system.

Want to use the system features. "Review the parent class feature. Create a Subclass object invocation function.

Note: The origin of the parent class is actually extracted from the common content of things.

So what is defined in the parent class is the most basic, most common function in the system. After the inheritance appears. The code also has some features: 1, variable. A member variable that has the same name defined in the child parent class. To use a variable of the same name in the parent class, the subclass needs to be distinguished by using Keywordsuper. This is generally not the case. Subclasses do not need to be defined because they are in the parent class.

And when the parent class is defined. General variables are privatized. 2. Function.

Subclasses have direct access to non-private member functions in the parent class. Special case: Overwrite occurs when a method that is identical to the parent class is defined in a subclass. Most refer to non-static methods. Finally, the method of the subclass is executed, and the parent class is equivalent to being overwritten. There is also a feature of the function: Overwrite (rewrite, duplicate). When do you use it? When the function of the parent class is to be changed. Changing the source code is not recommended.

Because it was a disaster. Simply inherit the original class from a class and define a new upgraded function.

But the function is the same, only the realization method changes. This is a subclass that can follow the definition of a feature in the parent class and override the feature content. This is the overlay. The coverage is very cool, but there are a few things to note: 1. When the child class overrides the parent class, the permission must be greater than or equal to the parent class permission.

2, static cannot overwrite non-static. 3. constructor function. Constructors are able to initialize objects in this class, and also to initialize subclass objects.

Subclass Object Initialization: All construction methods in subclasses will access the constructor of the parent's hollow parameter. Because of the first row of each constructor, there is an implicit super statement.

Why do you have to have this statement? Because subclasses get the data in the parent class, you must first understand the initialization process of the parent class to the data. When there are no null parameter constructors in the parent class. The subclass constructor must use the Super clause to understand the constructor specified in the parent class to be interviewed. The subclass constructor was also able to access the constructors in this class through the this statement.

But it's definitely in the sub-category. At least one constructor will access the parent class.

Abstract class: In fact, in the analysis of things, things in the function of some of the content is not understood.

These things that do not understand are abstract. It is possible to describe a narrative through abstract functions. Abstract functions must be defined in an abstract class, because the class in which the abstract function is located also has to be identified abstractly. Features: 1, the abstract function simply declares the function. There is no function body. 2. Both abstract and abstract functions need to be decorated with an abstract. 3, abstract classes cannot be instantiated.

4, if you want to use abstract functionality, you must be able to instantiate a child class by overriding all of the abstract methods in the parent class. The subclass is an abstract class, assuming that only some of the abstract methods are covered. Can also be understood as: An abstract class is a parent class. is continuously drawn upward, during the extraction process. Only method declarations are extracted, but no method implementations are extracted.

Abstract classes are almost the same as half classes.

Difference: Abstract classes can define abstract methods. Abstract classes are not able to create objects. In fact, abstract classes are used to describe things as well as to define abstract methods. It is also possible to define non-abstract methods. Interface Initial understanding: The interface appears to be a special abstract class.

There are abstract methods in store.

Features: Format: 1, defined by interface. 2, common members in interfaces: constants, abstract methods. And these members have fixed modifiers. Constants: public static Final method: Public abstract 3, the members of the interface are collectively owned. 4. A class can realize multiple implementations of the interface, and also make up for the security hidden danger caused by multiple inheritance. So Java has made improvements to multiple inheritance. The multi-implementation method is used to embody the characteristics of multiple inheritance.

5, a class can inherit a class at the same time, implementing multiple interfaces. 6, the interface is an inheritance relationship with the interface, and can inherit more.

Application features: 1, interface is the rule of external exposure.

2, the interface is the extension of the function.

3, the appearance of the interface reduces the coupling. Don't forget to say it. Need an example. such as USB. Pci. Motherboard. Socket.

Abstract class and interface similarities and differences: the same: 1, can be defined in the internal abstract method.

2, usually on the top floor. 3, can not be instantiated, all need subclasses to implement. Differences: 1, abstract classes can define abstract methods and non-abstract methods, and interfaces can only define abstract methods. 2. The presence of interfaces can be implemented more. Abstract classes can only inherit one single inheritance.

That is, the presence of interfaces avoids the limitations of single inheritance.

3. The relationship between inheritance and implementation is inconsistent. Inheritance: is a, implementation: like a/*abstract class fu{abstract int show ();} Class Zi extends Fu{int Show1 () {return 3;}} Class Fu{void method () {System.out.println ("method Run");}} Class Zi extends Fu{void method () {System.out.println ("method Zi Run");}} Class Arraytool{public int Getmax (int[] arr) {}priavte int age;public void Setage ()} athlete |--basketball player: |--football player: */




Multi-State Summary:

Abstract class Animal {abstract void Eat ();} Class Dog extends Animal {public void Eat () {//Bone;}} Class Cat extends Animal {public void Eat () {//eat fish;}}class Pig extends animal {public void Eat () {//feed;}}class demo{public void Method (Animal x )//new Dog (); New Cat (); {x.eat ();} /*public void Method (Cat x) {x.eat ();} public void Method (Dog x) {x.eat ();} public void method (Pig x) {x.eat ();} */}class main{public static void Main (string[] args) {Demo d = new Demo ();d. Method (New Dog ());d. Method (New Cat ());}} Animal x = new Cat (). Cat x = new Cat ();

Performance: a reference to a parent class or interface points to or receives its own subclass object.

Two.

Prerequisite: 1, the class must have a relationship with the class.

Inherit, implement. 2. Usually there is coverage. Three. Advantage: A pre-defined program can execute the contents of a post-program. Enhanced the extensibility of the program. Four. Cons: Despite being able to be used in advance, you can only access the functionality that is already in the parent class and perform the functional content of the later subclasses. Special features defined in subclasses cannot be used in advance. Five. Considerations for polymorphism: in code.

For member functions: Fu f = new Zi (); F.method (); compile time: Look to the left. Execution period: look to the right.

Because the member function has an overwrite operation. For non-private instance variables. Static variables, static methods.

Both compilation and execution look to the left. The teacher asked to remember the conclusion. Have spare time, just think about why? Six. Transformation. The subclass object is referenced by the parent class: The subclass object is transformed upward. Converts the parent class that points to the subclass object to a subclass type reference: down transformation. Seven. Used by the application computer. Motherboard execution.

Class Mainboard{public void Run () {//motherboard execution;} public void Usepci (PCI p)//pci p = new netcard (); {if (p!=null) {P.open ();p. Close ();}}} To improve the scalability of the motherboard functionality.

Defines a rule.

Let the late appearance of the functional plate. This motherboard can be used only if the rule is overwritten. Interface pci{void open (); void close ();} Class Maindemo{public static void Main (string[] args) {mainboard mb = new mainboard (); Mb.run (); Mb.usepci (null); MB.USEPCI (New netcard ());}} Class Netcard implements pci{public Void Open () {}public void Close () {}}object: is a direct or indirect parent class for all objects in Java.

All the methods in it are available to all objects. Common method: Boolean equals (Object obj): Used for a comparison of two objects.

String toString (): Gets the string representation of the object class name @ hash value getclass (). GetName () + "@" +integer.tohexstring (hashcode ()); Class getclass (): Gets the object of the bytecode file to which the object being executed belongs.

That is, assume that the demo d = new demo ();d. GetClass (): Gets the bytecode file Demo.class object that the object to which D is executing belongs to.

Typically when you define an object yourself. Because the object has its own special descriptive narrative, it will establish a specific method of the object itself, or a string representation. In other words, the method in object is overwritten. /*demo D1 = new demo ();D Emo d2 = new Demo ();d 1.getClass () = = D2.getclass (); */class demo//extends object{public String to String () {This.getclass (). GetName () + "#" +integer.tohexstring (This.hashcode ());}} Class Fu{void Show () {System.out.println ("Fu Show");}} Class Zi extends Fu{void function () {super.show ();//this.show ();} void Show () {System.out.println ("Zi Show");}} /*class computer{private mainboard MB; Computer () {MB = new mainboard ();} public void Play () {Mb.run ();}} */






Summary of exceptions

Exception: What is it? is a descriptive narrative of the problem. Encapsulates the problem into an object. ------------anomaly System: The characteristics of throwable|--error|--exception|--runtimeexception anomaly system: All the classes in the anomaly system and the objects that are built have the ability to be parabolic. This means that it can be manipulated by throw and Throwskeyword. Only abnormal systems have this feature. --------------the use of throw and throws: Throw is defined within a function and is used to throw an exception object. The throws is defined on the function. Used to throw an exception class that can throw multiple separated by commas. Throws an exception object when the function content has a throw. Try processing is not performed.

Must be declared on the function. Otherwise, the compilation fails. Note that runtimeexception is excluded. It also says that the runtimeexcpetion exception that is thrown in the function is assumed. function can not be declared. --------------assume that the function declares an exception and the caller needs to handle it. The processing method can be throws to try. There are two kinds of exceptions: at compile time, the exception is detected at compile time. Assuming no processing (no throwing and no try), the compilation fails. The exception is identified, which means that this can be handled. Runtime exceptions (compile-time misconduct) are not processed at compile time, and the compiler does not check. This exception occurs and is not recommended for processing, so the program stops.

The code needs to be corrected. --------------exception Handling statement: The code that try{needs to be detected;}catch () {The code that handles the exception; The code that}finally{is bound to run;} has three binding formats: 1.try{}catch () {}2.try{}finally{} 3.try{}catch () {}finally{} NOTE: The general definition in 1,finally is to close the resource code. Because the resource must be freed. 2,finally there is only one situation that will not run. When run to System.exit (0); fianlly will not run.

--------------define the exception yourself: Define the class to inherit exception or RuntimeException1, in order for the class of its own definition to be parabolic. 2, let the class have the common method of operation exception. When you want to define the information for which you define the exception. Ability to use functions already defined by the parent class. The exception exception information is passed to the constructor of the parent class.

Class MyException extends Exception{myexception (String message) {super (message);}} Define your own exceptions: In accordance with Java's object-oriented thinking, the unique problems appearing in the program are encapsulated. Advantages of--------------Exception: 1. Encapsulate the problem.

2, the normal process code and problem-handling code are separated, the party is easy to read. Exception handling principle: 1, there are two ways of processing: try or throws. 2, called to throw the exception when the function. Throw a few. Just deal with a few.

A try corresponding to multiple catch. 3, multiple catch, and the parent class catch is placed to the most of the following. 4,catch inside. Need to define a targeted approach. Do not simply define printstacktrace, output statements. and do not write. The exception to be caught. When this feature is not processed, it can continue to be thrown in the catch. Try{throw new Aexception ();} catch (Aexception e) {throw e;} Assume that the exception is not handled, but it does not belong to the exception that is present with the feature. The ability to convert an exception after the exception is thrown and associated with that function. Or an exception can be handled when it is necessary to provide an exception to the problems associated with this function, when the caller knows. and processing.

Can also be caught after the exception is processed. Converts a new exception. Try{throw new Aexception ();} catch (Aexception e) {//For aexception processing. throw new Bexception ();} Example. Examples of remittances. Exception considerations: When the child parent class is overwritten: 1. The exception that the subclass throws must be a subclass or a subset of the exception of the parent class. 2, if the parent class or interface does not throw an exception, the subclass overrides the exception, can only try not to throw.





Summary of the collection:

Collection: Ability to store multiple objects of different types. Proactively expand capacity architecture as the number of storage objects increases:collection<e> |----List: The object being deposited is ordered. And can be repeated ArrayList: the underlying data structure used is an array, the thread is unsafe, Find Fast, and delete slow Vector: the underlying data structure used is an array. Thread-safe, Find Fast. Delete Slow LinkedList: the underlying data structure used is a linked list. The thread is not secure. The lookup is slow. Quick and delete Speed |----Set: The object being deposited is unordered. And can not be repeated HashSet: the underlying data structure is a hash table, the thread is insecure to ensure that the object is the only principle: first infer the hashcode () value, the assumption is different directly increase the collection. Assuming that the hash value is also called the Equals () method, assuming that the Equals () method returns a value of True, the object is found to exist in the collection and does not increase the collection TreeSet: the underlying used The data structure is a two-fork tree. Thread insecurity sorts the objects that are stored in the collection to ensure that the objects in the collection are unique: based on whether the return value of CompareTo () or compare () is 0 rows                                Order form One: Make the objects in the collection have comparability so that the class to which the objects in the collection belongs is implemented in the Comparable<t> interface. int CompareTo (T-t) method Sort by two: Let the collection have the sort function to define a comparison device.                    Implement an int compare (T t1,t T2) method in the Comparator<t> interface to pass the comparison object as a parameter to the Treeset<e> collection's construction method When an object in the collectionWith comparability, and when there is a comparison device, the preference of the generic:< reference data type > The execution time issue to the compile time without forcing the type conversion class Demo<t> {PU          Blic void Show (T-t) {}//self-using generic method public <E> void Fun (E e) {} The static method can only use the generic public static <W> void func (W) {}}//generic definition on the interface interface inter<    t> {} wildcard character:? Generic-qualified:? Extends E and? Super Emap<k,v>: A separate interface. Stored is a key value pair, the key can not be repeated, unordered HashMap: Guaranteed key only principle and hashset like, hashcode (), Equals () Treemap:treemap is based on the key to sort, guarantee the key only principle and TreeSet Similarly, depending on whether the return value of compareTo () or compare () is 0, 0 is the iterative way of repeating a key map in two ways: the first: set<k> keys =map.ke                 Yset ();                 iterator<k> ite = Keys.iterator ();                    while (Ite.hasnext ()) {K key = Ite.next ();                    V value = Map.get (key);                 System.out.println (key+ "," +value); } Another type: Set<map.                entry<k,v>> Entry = Map.entryset ();                iterator<map.entry<k,v>> ite = Entry.iterator ();                   while (Ite.hasnext ()) {map.entry<k,v> en = Ite.next ();                   K key = En.getkey ();                   V value = En.getvalue ();                System.out.println (key+ "," +value); } Tool Class: Arrays collections Enhanced for loop variable-parameter static import






Test topic:

A: Jane answers

1. Two object values are the same (x.equals (y) = = true). However, there can be different hash values. This sentence is incorrect (5 points )
Right

2. Can the interface inherit the interface ? can the abstract class implement the (implements) interface?

Can abstract classes inherit entity classes ?

(5 points )

Can, can. Can

3. There is a return statement in try {}. Then the code in the finally {} immediately after this try will not be run and when it is run. Before or after the return ?

(5 points )
Will, before return

4. the difference between String and stringbuffer (5 points )
StringBuffer joins a string that belongs to an object. Adding a string creates a new constant

Two: Programming questions

1: Calculate payment amount : a cup of 5 Yuan , every two cups of the Second Cup half price ( number of cups entered by the user from the keyboard ) such as : 5 cups = (5+2.5) * + 5 = + (Ten minutes )

2: Statistics of the number of odd and even digits of the string "123456789012" respectively (ten minutes )

Adds the odd digit number of a string to sum C1 = 1 + 3 + 5 + 7 + 9 + 1

Add the number of even digits of a string to sum c2 = 2 + 4 + 6 + 8 + 0 + 2

3:string[] cards = {"3", "4", "8", "A", "K", "Q"} Array stores 6 cards , design an algorithm to disrupt the card, that is, to realize the shuffle function (Ten points )

4: a 5-bit integer that infers that it is not a palindrome number. For example, 12321 is a palindrome number (10 points)

5: Inserts a number into an ordered array of integers, and the array is ordered after it is inserted

( using dichotomy ) ( in minutes )

6: implement randomly generated color ball number : For example : [Geneva] [] [ score ]

a red ball (01~33) takes six

A blue ball (01~16) takes a

Tips :

Blue Ball Pool {"01", "02", "03", "04", ... "+"}

Red ball Pool {"01", "02", "03", "04", ... "*"}

Use tags {f, F, F, F, ... f}

The result is stored in an array that can be used to append the new " Ball number " to the array expansion.

Handling logical references such as the following procedures :

1 randomly generated red ball sequence number

2 Check if " red ball serial number " has been used ( removed )

Assume that you have used return 1

3 Remove a red ball , set the use Mark to true

4 Did you remove 6 red balls ?

Assuming there are no more than 6 , return 1

5 Sorting the results of the red ball

6 take out a basketball to the result


java-day08 pm-Summary, test

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: info-contact@alibabacloud.com 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.