Object-oriented basics 3 (class0523)

Source: Internet
Author: User
Tags scream try catch

How to Implement the polymorphism 2-Interface

An interface defines a capability that specifies what a subclass can do. It is similar to an abstract class and solves a single inheritance of a class. Interface can implement multi-Inheritance

Case

Bird-Sparrow, ostrich, penguin, parrot

A bird can fly an ostrich, but a penguin cannot... What do you do

Exercise: for students, teachers, and parent class persons, define an interface for photography iphotographable and an interface for singing isingable.

Subclass inherits abstract classes and implements Interfaces

The members in the interface must not be implemented.

The interface members cannot have access modifiers, which are implicitly exposed.

The interface can have attributes, methods, indexers, and so on, but cannot have fields. All Programs in the constructor interface must be fully implemented in the quilt class.

 

Rubber Duck, wood duck, real duck. The three ducks can swim, while the Rubber Duck and the real duck will scream, but the sound is not the same. The rubber duck will scream, and the real duck will scream, but the wooden duck will not.

The principle of opening and closing is mainly reflected in two aspects:

Open to expansion means that existing code can be expanded to adapt to new situations when new requirements or changes exist.

. Closed modification means that once the class is designed, its work can be completed independently without any modification to the class.

When to use abstract classes and when to use interface abstract classes are mainly used for closely related objects. interfaces are suitable for providing general functions for irrelevant classes.

1. Planes fly and birds fly. They all inherit the same interface "fly". However, f22 belongs to the aircraft abstract class and pigeon belongs to the bird abstract class.

Interview Questions

1. How to use virtual and override?

2. How to Use abstract and override?

3. Is "overload", "Rewrite", and "hide" the same concept?

4. Differences between abstract classes and interfaces

Differences between abstract classes and interfaces

Public capabilities of Interface Definition classes, public Implementation and Public capabilities of abstract class definition classes

A class can inherit only one class (abstract class), but multiple interfaces can be implemented at the same time.

The interface cannot be implemented. The abstract class can contain unimplemented members or implemented members.

Methods not implemented in the interface must be directly implemented in the subclass. unimplemented members in the abstract class must be rewritten in the subclass.

A good interface definition should be specific and functional, rather than multi-functional, otherwise it will cause interface pollution.

If a class only implements a function of this interface and has to implement other methods in the interface, it is called interface pollution.

When to use abstract classes and when to use interfaces

Abstract classes are mainly used for closely related objects. interfaces are suitable for providing general functions for unrelated classes.

1. Planes fly and birds fly. They all inherit the same interface "fly". However, f22 belongs to the aircraft abstract class and pigeon belongs to the bird abstract class.

2. just like all doors (abstract class), I can't give you a door (I can't instantiate it), but I can give you a specific door or wooden door (polymorphism ); it can only be a door. You cannot say it is a window (single inheritance); a door can have a lock (Interface) or a doorbell (multiple implementations ). A door (abstract class) defines what you are and an interface (LOCK) specifies what you can do (one interface is best to do only one thing, you cannot require the lock to make sound (interface pollution )).

Type conversion cast

Implicit and explicit conversions. If the target type is sufficient for source type conversion, implicit conversion is required; if the target type does not necessarily meet the requirements of source type conversion, explicit conversion is required (the programmer is responsible for this ).

Example: Double D = 5; int n = 6; double num = N;

Implicit conversion is used to convert students into students, and explicit conversion (forced conversion) is used to convert students into students)

Student s = new student (); person P = s; Student Stu = (student) P;

Implicit conversion can be performed only between types with Intersections in the memory storage. Cast is not allowed, string/INT is converted, and convert is only allowed. Convert. toint32/convert. tostring

Cast is a type conversion at the memory level. The data in the memory remains unchanged, but the viewing angle is different.

Type conversion convert

To convert other types, you can use convert. toint32, convert. tostring, and so on.

Convert can convert the object type to another type and convert the string to an integer. You can also use Int. parse Int. tryparse

String STR = NULL;

Int num = 0;

Num = convert. toint32 (STR );

Console. Write (Num + "\ r \ n ");

Num = int32.parse (STR );

Console. Write (Num + "\ r \ n ");

Int32.tryparse (STR, out num );

Console. Write (Num + "\ r \ n ");

Running result: convert. if toint32 () is null, 0 is returned instead of an exception. If int32.parse () is null, an exception is thrown. If int32.tryparse () is not thrown, true or false is returned to indicate whether the resolution is successful. If the parsing is incorrect, the caller will get a value of 0. Efficiency int32.tryparse () is better than int32.parse () than convert. toint32 (). Because: convert. toint32 will delegate the final parsing work to int32.parse, while int32.parse and int32.tryparse respectively proxy the parsing work directly to number. parseint32 and number. tryparseint32: the former throws an exception when a parsing error occurs, while the latter returns only false.

Exception Handling

Case:

Int x = 5; int y = 0; int z = x/y;

An error occurred while running the program. Subsequent content cannot be run.

Once a program has a function exception, the entire program crashes and other functions cannot run normally.

Try catch. Exception ex exception is also an object.

Main attributes of the exception class: Message and stacktrace

When an exception occurs, the program exits by default, and subsequent code in the try code block will not be executed. Code after catch will continue to be executed.

Throw your own exception, throw: throw, and catch

1 try is used to check for exceptions and help send any possible exceptions. 2. Catch handles errors in a way with greater control. Multiple catch clauses are allowed. 3 finally, whether or not an exception is thrown, the finally code block will be executed. 4 5 6 static void processstring (string s) 7 {8 If (S = NULL) 9 {Throw new argumentnullexception (); 10} 11} 12 static void main () 13 {14 try {string S = NULL; processstring (s) ;}// most specific: 15 catch (argumentnullexception e) 16 {17 console. writeline ("{0} first exception caught. ", e); 18} // least specific: 19 catch (exception e) {console. writeline ("{0} second exception caught. ", e );}}

Value Type reference type

The painter drew two pictures.

Value types are implicitly derived from system. valuetype

Numeric type, bool, structure, enumeration

The reference type is derived from system. object.

String, array, class, interface, etc.

The value assignment of the reference type variable only copies the reference to the object, instead of copying the object itself. When a value type variable is assigned to another value type variable, the included values are copied.

Enum gender {male, female} Enum weeks {Sunday = 0, Monday,}, a constant related to the enumerated value, converts the string to an enumeration gender G = (gender) enum. parse (typeof (gender), "male"); the structure is a small class, and the value type cannot inherit from the class. Implicit sealing can be achieved. The interface cannot have a display without a parameter Constructor (implicit) fields cannot be assigned an initial value in the structure. If you use the constructor to initialize the structure, you must assign values to all fields in the constructor.

Function return value (modifier before function parameters)

Variable Params Parameters

Ref is just an address, which is passed by reference. You can forcibly change the value to be passed by reference.

Out allows the function to output multiple values.

Ref must be initialized first, because it is a reference, so it must be "have" before it can be referenced, while out is an internal value assigned to the external, so Initialization is not required, and external Initialization is useless.

In the method, you must assign a value to the out parameter. In the application scenario, the external value is changed internally. In the out method, the external variable is assigned an internal value, out is generally used when a function has multiple return values.

Case 1: exchange of two variables

Case 2: Simulate login and return whether the login is successful. If the login fails, the system prompts whether the user name is incorrect or the password is incorrect.

Calculate the maximum, minimum, and average values in the array to allow the content in the array to be swapped

Common Class Libraries

Learning. NET is to learn how to use countless class libraries,

Let's first look at two simple string strings, which are immutable.

A string can be viewed as a character array.

Attribute

Length

Method

Isnullorempty ()

Static Method

Tochararray ()

Tolower ()

Toupper ()

Equals () case-insensitive comparison

Join () Static Method

Format () Static Method

Indexof ()

Lastindexof ()

Substring ()

Split ()

Replace ()

Trim ()

Job:

1. to implement three types of mobile storage devices: USB flash drive, MP3 player, and mobile hard disk, the computer must be able to exchange data with these three devices. In the future, there may be new third-party mobile storage devices, therefore, the computer must be scalable and can exchange data with storage devices that are not yet known. The reading and writing methods vary between storage devices. There are only two methods for USB flash drives and mobile hard drives. mp3player also has a playmusic method.
Change to interface

2. Guessing games + Enumeration
3. Calculate the maximum, minimum, and average values in the array.
4. Place the content in the array
5. Review object-oriented (mainly abstract class object-oriented calculator)

 

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.