java-day08 pm-Summary, test

Source: Internet
Author: User
Tags define abstract throw exception

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 and does not support multiple inheritance. Why is it? Answer: The subclass object is not sure which one to run because it inherits more than one parent class if there is the same method. 2,java also supports multilayer inheritance. A-->b--->c can form a succession system. To use the system function, "Look up the parent class function, establish the 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, there are some features on the code: 1, variables. When a member variable of the same name is defined in the child parent class, the subclass must use the keyword super to distinguish it from the variable with the same names in the parent class. This is generally not the case, because there is a parent class in which the subclass does not need to be defined. And when the parent class is defined, the general variables are privatized. 2, function. Subclasses can access directly 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.  The method that eventually runs the subclass, the parent class is equivalent to being overwritten.  Another feature of the function: Overwrite (rewrite, duplicate).  When do you use it? When the function of the parent class is to be modified, it is not recommended to modify the source code.  Because it's a disaster.  As long as you inherit the original class from a class, define a new post-upgrade feature. But the function is the same, but the implementation 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.  Coverage is cool, but there are caveats: 1, when a subclass overrides a parent class, the permission must be greater than or equal to the parent class permission. 2, static cannot overwrite non-static. 3, constructor. Constructors can initialize objects in this class, or they can initialize child class objects. Subclass Object Initialization procedure: all constructors in subclassesMethod accesses the constructor of the parent's hollow argument, because the first row of each constructor has an implicit super statement. Why do you have to have this statement? Because subclasses obtain data from the parent class, you must first clarify the initialization process of the parent class to the data. When there is no empty argument constructor in the parent class, the subclass constructor must explicitly define the constructor specified in the parent class to be accessed through the Super clause. The subclass constructor can also access constructors in this class through the this statement. However, it is certain in subclasses that at least one constructor will access the parent class. Abstract class: In fact, in the analysis of things, things in the function of some are ambiguous content. These ambiguous content is abstract. Can be described by abstract functions. Abstract functions must be defined in an abstract class, because the class in which the abstract function is located must also be identified abstractly. Features: 1, abstract function is only declared function, there is no function body. 2, abstract classes 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 override all the abstract methods in the parent class by subclasses before you can instantiate a subclass. If only part of the abstract method is overridden, then the subclass is an abstract class. Can also be understood as: abstract class is a parent class, is constantly drawn upward, in the extraction process, only the method declaration is extracted, but not the extraction method implementation. Abstract classes are about the same as half classes. Difference: Abstract classes can define abstract methods. Abstract classes cannot be set up for objects. In fact, abstract classes are used to describe things, either to define abstract methods or 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 common. 4, a class can be multi-implementation of the interface, but also to compensate for the security implications of multiple inheritance, so Java to the multi-inheritance has been improved. The multi-implementation method is used to embody the characteristics of multiple inheritance. 5, a class can inherit a class and implement multiple interfaces at the same time. 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, you need an example. such as USB. PCI, motherboard. Socket. Abstract class and interface similarities and differences: the same: 1, you can define the abstract method internally. 2, usually on the top floor. 3, can not be instantiated, all need subclasses to implement. Different points: 1, abstract methods and non-abstract methods can be defined in an abstraction class, and an interface can only define abstract methods. 2, the appearance of the interface can be implemented more. Abstract classes can only be inherited by single. That is, the presence of an interface avoids single-inheritanceLimitations. 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, there will usually be coverage. Three. Benefit: A pre-defined program can run the contents of a post-program. Enhanced the extensibility of the program. Four. Cons: Although it can be used in advance, it only accesses the functionality that is already in the parent class and runs 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. Operating period: look to the right. Because the member function has an overwrite operation. For non-private instance variables, static variables, static methods. Compile and run all looking to the left. The teacher asked to remember the conclusion. When you have free time, 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. The motherboard is running. Class Mainboard{public void Run () {//motherboard run;} 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 lateThe feature palette that appears, can be used by this motherboard as long as 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 to compare whether two objects are the same. 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 running object belongs. That is, if 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 customize an object, because it has its own unique description, it creates a unique comparison method for 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 description 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 established are parabolic. This means that it can be manipulated by the throw and throws keywords. Only the anomaly system has this feature. --------------throw and throws usage: Throw is defined within a function and is used to throw an exception object. Throws is defined on a function, used to throw an exception class, and can be thrown multiple separated by commas. When the function content has a throw throw exception object, try processing is not done. Must be declared on the function, or the compilation will fail. Note that runtimeexception is excluded. It is also said that if the runtimeexcpetion exception is thrown within the function, the function may not be declared. --------------If the function declares an exception, the caller needs to process it. The processing method can be throws can try. There are two kinds of exceptions: compile-time is detected exception at compile time, if there is no processing (no throw and no try), the compilation fails. The exception is identified, which means that this can be handled. Runtime exceptions (not detected at compile time) at compile time, no processing is required and the compiler does not check. This exception occurs and is not recommended for processing, so the program stops. The code needs to be remediated. --------------exception Handling statement: try{The code that needs to be instrumented;}catch () {The code that handles the exception; code that}finally{is bound to execute;} has three binding formats: 1.try{}catch () {}2.try{}finally{} 3.try{}catch () {}finally{} Note: The resource code is usually closed as defined in 1,finally. Because the resource must be freed. 2,finally only one situation will not be enforced. When executed to System.exit (0); fianlly will not execute. --------------Custom Exception: Define class inheritance Exception or RuntimeException1, in order for the custom class to be parabolic. 2, let the class have the common method of operation exception. When you want to define the information for a custom exception, you can use the functionality 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);}} Custom exceptions: Encapsulate specific issues that arise in your program in the Java object-oriented mindset. -Benefits 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 an exception when the function throws several, on the handle several. A try corresponds to multiple catch. 3, multiple catch, the parent's catch is placed at the bottom. Within the 4,catch, it is necessary to define a targeted approach. Do not simply define printstacktrace, output statements. and do not write. When the exception is caught, the feature cannot be processed and can continue to be thrown in the catch. Try{throw new Aexception ();} catch (Aexception e) {throw e;} If the exception is not handled, it does not belong to the exception that is present with the feature. Exceptions can be thrown after the exception is cast 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. You can also convert a new exception after the catch exception is processed. Try{throw new Aexception ();} catch (Aexception e) {//For aexception processing. throw new Bexception ();} For 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 an exception, only try cannot throw.





Summary of the collection:

Collections: You can store multiple objects of different types and automatically expand the capacity architecture as you increase the number of storage objects:collection<e> |----List: The stored object is ordered and can be repeated ArrayList: the underlying data structure used is an array, a line Process is not safe, Find Fast, and delete slow Vector: the underlying data structure used is an array, thread-safe, Find Fast, and delete slow LinkedList: the underlying data structure is linked list, thread is not safe, find slow, delete speed Fast | | ---Set: The object being deposited is unordered and cannot be repeated HashSet: the underlying data structure used is a hash table, the thread is insecure to ensure that the object is the only principle: First Judge Hashcode (           ) value, if it is different directly into the collection, if the hash value is the same as in the call to the Equals () method, if the Equals () method returns a value of True, the object is considered to exist in the collection and does not join the collection TreeSet: The data structure used at the bottom is a two-fork tree, and thread insecurity sorts the objects that are stored in the collection to ensure that the objects in the collection are unique: Based on the return value of CompareTo () or compare ()                                is 0 sort one: let the objects in the collection have comparability so that the classes that are stored in the collection are implemented in the Comparable<t> interface. int CompareTo (T t) method sort by two: Let the collection have the sort function to define a comparator, real                    The int compare (T t1,t T2) method in the Comparator<t> interface passes the comparer object as an argument to the Treeset<e> collection's construction method When the objects in the collection haveComparability, and the comparator is present, the comparator takes precedence over the generic:< reference data type > shifts the runtime issue to the compile time without forcing the type conversion class Demo<t> {Publ          IC void Show (T-t) {}//self-use 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&LT;T&G    T    {} wildcard characters:? Generic-qualified:? Extends E and? Super Emap<k,v>: A separate interface that stores key-value pairs, keys cannot be duplicated, unordered HASHMAP: Guaranteed keys are the only principle and HashSet, hashcode (), Equals () treemap:tr                 Eemap is sorted according to the key, the guarantee key only principle and treeset the same, according to CompareTo () or compare () The return value is 0, 0 is considered to be duplicate key map iterative way There are two: the first kind:                 set<k> keys =map.keyset ();                 iterator<k> ite = Keys.iterator ();                    while (Ite.hasnext ()) {K key = Ite.next ();                    V value = Map.get (key);                 System.out.println (key+ "," +value); } The second 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 questions:

A: Jane answers

1. Two object values are the same (x.equals (y) = = true), but can have different hash values, this sentence is right (5 points )
Right

2. Can interfaces inherit interfaces ? can an abstract class implement (implements) interfaces? Can abstract classes inherit entity classes ? (5 points )

Yes, yes, you can.

3. Try {} has a return statement, then the code immediately following the try of the finally {} will not be executed, when executed, before or after the return ? (5 points )
Will, before return

4. the difference between String and stringbuffer (5 points )
StringBuffer adds 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 determines whether it is 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 takes an array store , and the array can be appended with the new " Ball number " using the array expansion.

The process logic reference is as follows :

1 randomly generated red ball sequence number

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

Returns 1 if used

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

4 Did you remove 6 red balls ?

If not to 6 , return 1

5 Sorting the results of the red ball

6 take out a basketball to the result


java-day08 pm-Summary, test

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: 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.