Java getting started -- (3) getting started with objects (below)

Source: Internet
Author: User
Tags define abstract try catch

Java getting started -- (3) getting started with objects (below)
Keywords: class inheritance, final keywords, polymorphism, interfaces, exceptions, packages, access control I. class inheritance 1. Class Inheritance refers to building a new class, the new class is called a subclass. The existing class is called a parent class. The subclass automatically owns all the attributes and methods that can be inherited by the parent class.ExtendsKeyword.

class A{}class B extends A{}

 

Inheritance in Java: ① Java allows single inheritance. Multi-inheritance is not directly supported, and multiple inheritance is embodied in other methods. ② Single inheritance: a subclass can only have one parent class.
Class A {} class B {} class C extends A, B {} // class C cannot inherit both class A and class B
③ Multi-inheritance: a subclass can have multiple parent classes, which are embodied in multiple implementations. ④ Multi-inheritance: inheritance system. When learning the inheritance system, you should refer to the content in the top-level class to understand the basic functions of this system. To use this system function, you need to create the objects of the most subclass. (Look at the top layer and build the bottom layer .) 2. override: the sub-parent class defines the same function. Running result: the subclass function is running. This is another feature of the function in the Child parent class: override (rewrite, overwrite, and rewrite ). Notes for rewriting:

① The Child class overwrites the parent class, and the permission must be greater than or equal to that of the parent class.

② Static coverage static.

③ The statement must be exactly the same, and the list of Return Value Type function names and parameters must be the same.

3. super keyword

① Constructor features in the sub-parent class: when the sub-parent class has constructor, execute the constructor of the parent class before executing the constructor of the sub-class, this is because the first row of all constructors of the subclass has an implicit statement super (); // by default, the constructor that calls null parameters in the parent class. Why does the constructor In the subclass have an implicit super ()? Cause: the subclass inherits the content of the parent class. Therefore, when initializing the subclass, you must first perform the initialization action of the parent class in the parent class. To make it easier to use the content in the parent class. If no parameter constructor exists in the parent class, the constructor of the Child class must be an explicit super statement to access the constructor in the parent class. Details:

① If the first line of the constructor of the subclass writes this to call a constructor that deviates from other constructor, the super statement that calls the parent class does not exist because this () or super (), only in the first line of the constructor, because the initialization action must be executed first.

② Is there an implicit super in the parent class constructor? Yes, as long as it is a constructor, the first line by default is super ();

Who is the parent class of the parent class? Which of the following constructor is called by super? In the Java System, a parent class object of all objects is defined. Summary: The constructor in the class has an implicit super () statement in the first line by default. It accesses the constructor in the parent class. Therefore, the constructor of the parent class can initialize both the own object and its own subclass object. If the default implicit super statement does not have the corresponding constructor, the constructor called must be clearly defined in the constructor in the form of this and super. Super application: ① The application of the subclass instantiation process is also the application of super call.

② As long as the specified initialization action of the parent class is used, it is called in the subclass in the super (parameter list) format.

Usage of the super Keyword:

① Use the super keyword to call the member variables and member methods of the parent class. Specific format:

Super. member variable super. Member method ([parameter 1, parameter 2 ......])

② Use the super keyword to call the constructor of the parent class. The specific format is as follows:

Super ([parameter 1, parameter 2 ......]) The code that calls the parent class constructor through super must be located in the first line of the subclass constructor and can only appear once. When defining a class, if there are no special requirements, try to define a construction method without parameters in the class to avoid errors during inheritance. Disadvantages of inheritance: Breaking encapsulation. Ii. final keywords 1. final modifiers can be used to modify classes, methods, and variables (member variables, local variables, and static variables ).

① The final modified class is a final class, which cannot be inherited or derived from a subclass.

② The final modification method is the final method and cannot be rewritten. If you do not want to overwrite the quilt class when defining a method in the parent class, you can use the final keyword to modify the method. For example: public final void shout (){}

③ The final variable is a constant and can only be assigned one value.

For example, final int num = 2;

2. [When will final constants be defined in the program ?] When a piece of data is used in the program, it is fixed. To increase readability, you can name the data. This is a variable. To ensure that the value of this variable is not modified, the final modifier is added. This is a constant with high readability. Writing specification. All the letters in the constant name modified by final are capitalized. If multiple words are connected. Iii. abstract classes and interfaces 1. abstract classes: when describing a thing, there is not enough information to describe a thing, then it is an abstract thing. Classes that define abstract functions must also be modified by abstract keywords. classes that are modified by abstract keywords are abstract classes. The class of the abstract method must be declared as an abstract class, but the abstract class can not contain any abstract method, as long as the abstract keyword is modified. [Abstract class features]

① Abstract classes and abstract methods must be abstract. (Abstract methods must be defined in abstract classes ).

// Define the abstract class Animalabstract class Animal {// define the abstract method shuot () abstract int shout ();}

② An abstract class cannot be used to create an instance. The reason is: calling an abstract method does not have a method body.

③ The subclass can be instantiated only when all abstract methods in the abstract class are overwritten. Otherwise, this subclass is still an abstract class.

The reason for inheritance is more about thinking. It is easier to face common operations. 2. interface: if all the abstract methods in a class are abstract, you can define the class in another way, that is, the interface. When defining an interface, you must use the interface keyword to declare it, for example:
1 interface Animal {2 int ID = 1; // defines the global variable 3 void breathe (); // defines the abstract Method 4 void run (); 5} // Animal is an interface. The methods and variables defined in the interface contain some default modifiers "public abstract" (abstract method) "public static final" (global variable ).
Interface features:

① Interfaces can be used to create objects;

② Subclasses can be instantiated only when all abstract methods in the interface are overwritten. Otherwise, the subclass is an abstract class.

③ Multi-interface implementation example:

Interface Run {program code .....} Interface Fly {program code .....} Class Bird implements Run, Fly {program code .......}
Define a subclass to overwrite the interface: The subclass must have a relationship with the interface. The relationship between the class and the class is inherited, and the relationship between the class and the interface is implemented by using the keyword implements. The most important embodiment of interfaces: Solves the disadvantages of Multi-inheritance. The mechanism of Multi-inheritance is implemented too much in Java. Disadvantages of Multi-inheritance: when multiple parent classes have the same function, subclass calls will produce uncertainty. The core reason is that the function of the parent class has a subject, which leads to the uncertain subject content to be run during the call. The functions in the interface do not have a method body, which is defined by the subclass. If the subclass wants to inherit and extend functions of other classes, it can be implemented through the interface:
Class Dog extends Canidae implements Animal {// inherit first, then implement the program code ......}
The parent class defines the basic functions of things and interfaces define the extended functions of things. Some details after the interface appears: the class and the class are inherited, and the class and the interface are implemented; the interfaces and interfaces are inherited and can be inherited more. Iv. polymorphism 1. Summary of polymorphism [embodiment] references of the parent class or interfaces point to their own subclass objects. Dog d = new Dog (); // The type of the Dog object is Animal a = new Dog ();/the type of the Dog object is Dog on the right and Animal on the left. [Benefit] improves program scalability. [Disadvantage] When a subclass object is referenced by a parent class, only existing methods in the parent class can be used, and methods specific to the subclass cannot be used. [Prerequisite] ① It must be related, inherited, and implemented. ② There are usually rewrite operations.
1 // define the interface Animal 2 interface Animal {3 void shout (); 4} 5 // define the Cat class to implement the Animal interface 6 class Cat implements Animal {7 // implement shout () method 8 public void shout () {9 System. out. println ("meow... "); 10} 11} 12 // define the Dog type to implement the Animal interface 13 class Dog implements Animal {14 public void shout () {15 System. out. println ("Wang"); 16} 17} 18 // define test class 19 public class Example13 {20 public static void main (String [] args) {21 Animal an1 = new Cat (); // create a Cat object. Use the Animal type variable an1 to reference 22 Animal an2 = new Dog (); // create a Dog object, use animalShout (an1) of the Animal type variable an2 to reference 23 animalShout (an1); // call animalShout () method and pass an1 as a parameter to 24 animalShout (an2); // call animalShout, pass an2 as the parameter 25} 26 public static void animalShout (Animal an) {27. shout (); 28} 29}

Running result

Meow... Wang
[How to call the special method of subclass ?] Animal a = new Dog (); // Animal is a parent child object of the new Dog () type. However, when a parent type reference points to a subclass object, this improves the type of the subclass object (upward transformation ). Benefits of upward Transformation: improved scalability and hidden sub-types. Disadvantage: you cannot use a special sub-type method. If you want to use the special method of subclass, only child types can be used. You can perform downward and forced conversion.
Animal a = new Dog (); a. eat (); Dog d = (Dog) a; // convert a to the Dog type. Downward transformation. D. lookHome ();
When Will downward transformation be used? When you need to use the child-type special content. Note: No matter whether it is an upward or downward transition, the type of the subclass object changes. [Considerations for downward Transformation] Animal a = new Dog (); Cat c = (Cat) a; // The downward transformation is not clear about the specific subclass object type, therefore, classCastException (transformation exception) is easily thrown. To avoid this problem, we need to make a type judgment before the downward transformation. The keyword instanceof is used to determine the type.
If (a instanceof Cat) {// The type of the object to which a points is Cat. // Convert a to the Cat type. Cat c = (Cat) a; c. catchMouse ();} else if (a instanceof Dog) {Dog d = (Dog) a; d. lookHome ();}
Example:
1 interface Animal {2 void shout (); // define the abstract method shout () 3} 4 // define Cat class implementation Animal interface 5 class Cat implements Animal {6 // implement abstract method shout () 7 public void shout () {8 System. out. println ("meow... "); 9} 10 // defines the sleep () method 11 public void sleep () {12 System. out. println ("the cat is sleeping ..... "); 13} 14} 15 // define the Dog class to implement the Animal interface 16 class Dog implements Animal {17 // implement the abstract method shout () 18 public void shout () {19 System. out. println ("Wang... "); 20} 21} 22 // Define test class 23 public class Example14 {24 public static void main (String [] args) {25 Animal dog = new Dog (); // create a Dog class instance object 26 animalShout (dog); // call the animalShout () method and pass the dog as a parameter 27} 28 public static void animalShout (Animal animal) {29 if (animal instanceof Cat) {30 Cat cat = (Cat) animal; // force the animal object to Cat type 31 cat. shout (); // call cat's shout () method 32 cat. sleep (); // call cat's sleep () method 33} else {34 System. out. println ("this Animal is not a cat! "); 35} 36} 37}

Running result:

this animal is not a cat!
[Transformation Summary]

① When will it go up?

Improves program scalability and does not relate to subclass types (child types are hidden ). Do I need to use the special method of subclass? No. Go up.

② When will it go down?

When a special sub-type method is required. However, you must use instanceof to determine the type. Avoid classCastException. 2. Anonymous internal class format:
New parent class (parameter list) or parent interface () {// implement part of anonymous internal class}

Example

1 interface Animal {2 void shout (); 3} 4 public class Example18 {5 public static void main (String [] args) {6 animalShout (new Animal () {7 public void shout () {8 System. out. println ("meow... "); 9} 10}); 11} 12 public static void animalShout (Animal an) {13. shout (); 14} 15}

Running result

Meow...
3. The Object class is the root class of all classes and defines the functions of all objects. Generally, the toString () method of the Object is rewritten to return the specified information. Example:
1 class Animal {2/* // method for defining Animal name 3 void shout () {4 System. out. println ("animal name"); 5} */6 // rewrite the toString () method in the Object class 7 8 @ Override 9 public String toString () {10 return "I am an animal! "; 11} 12} 13 // define the test class 14 public class Example16 {15 public static void main (String [] args) {16 Animal animal = new Animal (); // create an Animal Class Object 17 System. out. println (animal. toString (); // call the toString () method and print 18} 19}

5. Exceptions

1. Inheritance System of the Throwable class

① Error class: it indicates the internal system Error or resource depletion Error generated during Java running. It is serious and the execution cannot be resumed only by modifying the program itself. ② Runtime Exception and compilation Exception: compile-time Exception: in Java, except for the RuntimeException class, that is, its subclasses are all compile-time exceptions. The feature is that the compiler detects exceptions. If an exception occurs, it must be handled. Otherwise, the program cannot be compiled.

Runtime exception: the RuntimeException class is a runtime exception in its subclass. The Compiler does not detect the exception and does not need to declare it.

③ Common Throwable Methods
Common Throwable Methods
Method Declaration Function Description
String getMessage () Returns the detailed message string of the throwable.
Void printStackTrace () Output The throwable and its tracing to the standard error stream.
Void printStackTrace (PrintStream s) Output The throwable and its tracing to the specified output stream.
2. try... catch and finally exception Capture: capture specific statements for exceptions in Java. Statement:
Try {// The statement to be detected} catch (ExceptionType (Exception class and its subclass) e) {// processing of ExceptionType}
Execute a program after an exception occurs.
Finally {// The statement to be executed}

Example

1 public class Example20 {2 public static void main (String [] args) {3 // The following Code defines a try... catch statement is used to catch exceptions 4 try {5 int result = divide (); // call divide () method 6 System. out. println (result); 7} catch (Exception e) {// handle exceptions 8 System. out. println ("the captured exception information is" + e. getMessage (); 9 return; // used to end the current statement 10} finally {11 System. out. println ("enter finally code block"); 12} 13 System. out. println ("program continues to run down... "); 14} 15 // The following method achieves two integers except 16 public static int divide (int x, int y) {17 int result = x/y; // define a variable result to record the result 18 return result for division of two integers; // return the result 19} 20}

Running result

The captured exception information is:/by zero into the code block

During program design, the finally code block is often used after try... catch to complete required tasks, such as releasing system resources. Note that when the System. exit (0) Statement is executed in try... catch, the Java VM is exited and no code can be executed.

Try catch finally combination:

① Try catch: detects exceptions in the Code and transmits the exceptions to catch for handling.

Exception capture and processing.
Void show () throws {// do not need throws try {throw new Exception ();} finally {}}

 

② Try finally: Perform exception detection on the Code. If no catch is detected, the exception will be thrown by the default jvm.

Exceptions are not captured and processed, but the resources enabled by the function need to be closed. All finally resources are only disabled.
Void show () {// throws try {throw new Exception ();} finally {}}

③ Try catch finally

Detects an exception and passes it to catch, and defines the resource release.

④ Try catch1 catch2 catch3 .........

3. throws keyword ① throws keyword Declaration the syntax format for throwing an exception is as follows: modifier return value type method name ([parameter 1, parameter 2…]) Throws ExceptionType1 [, ExceptionType2…] {} ② Declaration: identify the problem and report it to the caller. Format:
void show ()throws Exception{     throw new Exception();}
If a compile-time exception is thrown through throw in the function and captured, it must be declared through throws for the caller to handle the exception. 4. custom Exception format: throw Exception object example
1 class DivideByMinusException extends Exception {2 public DivideByMinusException () {3 super (); // call the construction method of Exception without parameters 4} 5 public DivideByMinusException (String message) {6 super (message); // call the construction method without parameters for Exception 7} 8} 9 public class Example26 {10 public static void main (String [] args) {11 try {12 int result = divide (4,-2); 13 System. out. println (result); 14} catch (DivideByMinusException e) {15 System. out. println (e. getMessage (); 16} 17} 18 public static int divide (int x, int y) throws DivideByMinusException {19 if (y <0) {20 throw new DivideByMinusException ("divisor is negative"); 21} 22 int result = x/y; 23 return result; 24} 25}
6. definition and use of packages 1. Java packages are used to store classes. classes with the same functions are usually stored in the same package. Example: 1 package cn. itcast. chapter04; 2 public class Example01 {....} The package Declaration can only be located in the first line of the Java source file. 2. Package Import
Import package name. Class Name;
3. Common packages ① java. lang: contains the core classes of the Java language, such as the String, Math, System, and Thread classes. The class in this package does not need to be imported using the import statement. The System automatically imports all classes in this package. ② Java. util: contains a large number of tool classes and collection classes in Java, such as Arrays, List, and Set. ③ Java.net: contains Java Network Programming related classes and interfaces. ④ Java. io: Contains classes and interfaces related to Java input and output. VII. access permission modifier permissions:

Access control level

 

In the same class

Under the same package

(With or without any relationships)

Different packages (subclass)

Different packages

(It does not matter)

Private

Y

     

Default)

Y

Y

   

Protected

Y

Y

Y

 

Public

Y

Y

Y

Y

 

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.