Java BASICS (1): java Basics

Source: Internet
Author: User

Java BASICS (1): java Basics
Definition class: access modifier class name {} access modifier such as: public, priate is optional class is declared class keywords according to naming rules, the first letter of the class name is capitalized for example: create a "person" class with key code: public class Person {}*********************************** * *********************** define attributes: the data type attribute name of the access modifier. The access modifier is optional except the access modifier. the syntax and declaration variables are the same for example: create a "person" class, the key code is public class Person {public String name; public String gender; public int age ;} **************************************** * ****************** definition method: access modifier return type Method Name (parameter type parameter name 1, parameter type parameter name 2 ,......) {} The access modifier is optional and the return type can be void. When the return type is void, it indicates that no return value is returned, you do not need to use the "return" keyword in the method body to return specific data, but you can use the "return" keyword to exit the method. The return type is not "void ", in the method body, you must use the "return" keyword to return the results of the corresponding type. Otherwise, the program will include "parameter type parameter 1, parameter type parameter 2,..." in the compilation error parentheses ,......" The parameter list is called a parameter list. A parameter list is required only when a parameter is passed for a method during method execution. It can be omitted if no parameter is required, but parentheses cannot be ignored, when multiple parameters are passed, use parentheses to separate them. For example, define a method in the "Person" class to describe the behavior of a Person's work. key code: public class Person {public String name; public String gender; public int age; public void work () {System. out. println (this. name + "working philosophy: striving for the dream );}} **************************************** * ****************** create and use objects: 1. Create an object class name object name = new Class Name (); new is the class name () on the left of the keyword to the right of the Data Type of the object called the class constructor example: create an object of the Person class. key code: Per Son lilei = new Person (); 2. Use the object name. property // name of the property object of the referenced object. method Name // method example of referencing an object: assign a value to the object property and call the public static void main (String [] args) {Person lilei = new Person (); lilei. name = "Li Lei"; lilei. gender = "male"; lilei. age = 22; lilei. work ();} **************************************** * ****************** member method: 1. parameters defined when a work () method is created with parameters are called formal parameters. When calling a method, the input parameter is called a real parameter. 2. Method overloading: if the method name is the same and the parameter list is different, the method overloading feature is formed: in the same class, the method name is the same, ********************************** * *********************** member variables: 1. member variables: attributes in the class, variables defined directly in the class, are defined outside the method. PS: You can assign an initial value to a member variable during declaration. If no value is assigned, java will give it a default value. The value of the basic data type is 0, the value of the reference type is null2, and the local variable is: variables defined in the method are usually assigned a value before use, otherwise, a compilation error occurs ************************************ * ********************** construction method: the main function is to initialize some data. The access modifier method name (parameter list) {method body} constructor does not return values. The default constructor does not have parameters, therefore, the parameter list is optional (the shortcut key for constructing a method without parameters by default: Alt +/). The method name of the constructor is the same as the class name. If a constructor with parameters is written, you must generate a constructor without parameters. For example, define a constructor for the Person class. key code: public class Person {public Person () {this. name = "Li Lei" ;}} multiple overloaded constructor methods can be defined in a class. this keyword is the default value for an object. Reference: each instance method contains a this reference variable, pointing to the object that calls this method because this refers to its reference within the object, therefore, this can only call instance variables, instance methods, and constructor methods. This cannot call class variables and class methods, and this cannot call local variables. 1) use this to call member variables to resolve conflicts between member variables and local variables with the same name. 2) use this to call the member method. 3) use this to call the overloaded constructor. It can only be used in constructor. It must be the first statement of the constructor method. Example: public Penguin (String name, string sex) {this. name = name; this. sex = sex;} public Penguin (String name, int health, int love, String sex) {this (name, sex); this. health = health; this. love = love ;} **************************************** * ****************** encapsulation steps: encapsulation: the variables are declared, assigned, and used twice in OOP mode (Declaration, assignment, and use ): 1. assign values to the encapsulated class declaration. 2. assign values to the attribute declaration in the encapsulated class. 1. Modify the visibility of the attribute to change the Person class. You can change the attribute from public to private. For example, private the property of the Person class. key code: public class Person {private String name; private String gender; private int age;} 2. Set setter/getter () method example: add the setter/getter () method to the private attribute of the Person class. key code: public class PrivatePerson {private String name; private String gender; private int age; public String getName () {return name;} public void setName (String name) {this. name = name;} public String getGender () {return gender;} public void setGend Er (String gender) {this. gender = gender;} public int getAge () {return age;} public void setAge (int age) {this. age = age ;}3. Set the attribute access restriction. At this time, the attribute is still not restricted, for more restrictions, see myeclipse --> practice --> SetPerson *********************** ************************************ definition package: the package name package is the keyword declaration. It must be the first non-Annotated statement in the java source file, and one source file can only have one package declaration statement, the design package must correspond to the file system structure. Therefore, when naming a package, follow the encoding rules below: a, a unique package name prefix is usually all lowercase ASCII letters, it is a top-level domain name com, edu, gov, net, and org, and usually uses the reverse order of the network domain name of the organization. For example, if the domain name is javagroup.net, you can declare the package name "pacage net. javagroup. mypackage" B. The subsequent parts of the package name vary according to the internal specifications of different organizations. Such naming conventions may consist of specific directory names to differentiate departments, projects, machines, or registration names, such as "package net. javagroup. research. powerproject "**************************************: package from big to lowercase: 1. The meaning of the Declaration package is to declare the location of the current Class 2. The meaning of the import package is to declare the location of other classes to be used in the current class // put the Person class into pack1 package cn. bdqn. pack1; public class Person {...... Code omitted} // put the PersonTest class into pack2 package // when using the Person class, you need to use import to import it to package cn. bdqn. pack2; import cn. bdqn. pack1.Person; public class PersonTest {public static void main (String [] atgs ){...... Omitting code }}************************************ * ********************** class member access modifier: scope: in the same class, the sub-classes in the same package can be private in any place, not by default, not by default, or by protected, or public, or * **************************************** * ***************** modify attributes of the static Keyword: static modified attributes are called static variables or class variables, and those without static modification are called instance variables. For example, keep the name, gender, and age attributes of the Person class, create a static modified attribute, and call it. key code: public Person {public String name; public String gender; public static int age; public static int PERSON_LIVE ;//...... Code omitted} // The above is the Person class code, and the following is the call code //...... The Code Person hanbing = new Person (); hanbing. name = "HAN Bing"; hanbing. gender = "female"; hanbing. age = 22; Person. PERSON_LIVE = 1; in actual development, the most common scenario for modifying attributes with the static keyword is to define constants modified with the final keyword. If you use the final keyword to modify a constant, it cannot be changed during the entire program running. It has nothing to do with the specific object. Therefore, you can use static modifier, such as "static final int PERSON_LIVE = 1" PS: 1. The constant name is generally composed of uppercase letters. 2. When declaring a constant, you must assign the initial value ********************** * ************************************ static keyword Modification method: static methods are called static methods or class methods. Methods without modifying the static keyword are called instance methods. For example, the showDetails () method in Person is modified with the static keyword and called. key code: public Person {public String name; public String gender; public static int age; public static void showDetails (String name, String gender, int age) {System. out. println ("name:" + name + ", gender:" + gender + ", age:" + age) ;}// the above is the Person code, the following code calls public class PersonTest {public static void main (String [] args) {Person liudun = new Person (); Person. showDetails ("Liu dun", "male", 23 );}} 1. You cannot directly access instance variables and instance methods in static methods. 2. In the instance method, you can directly call the static variables and static methods defined in the class ********************** * ************************************ four basic behaviors: 1) access modifier: Public Private protected default 2) return type: Yes: variable definition data type variable name not: void3) Method Name: similar to the class name specification, a, method name lowercase B, method name consists of multiple words, starting from the second word, the first letter uppercase c, Method Name meaning 4) parameters: some are: the declaration part of the variable (boolean flag) does not: () 5) method body: Scope {} a, parallel: multiple methods can be parallel B, nested: methods cannot be nested; nested procedures can be used to control the first basic behavior of {if () {}}: the access modifier does not return the type method name (none) {} example: public void add () {} Second Basic Behavior: access modifier does not return type method name (with) {} example: public void add (Int num1, int num2) {} 1. Variable declaration process: parameters in the form of a parameter 2. Variable assignment process: the Third Basic Behavior of a real parameter: access modifier: return type method name (none) {} example: public int add () {} 1. Keyword: return is followed by the variable name, the return type position writes the Data Type of the variable. 2. The Code cannot be written after the return statement. The fourth basic behavior is: the access modifier has the return type method name () {} combine the second and third types. Example: public int add (int num1, int num2) {}************************************** * ******************** inherited Syntax: in java, the access modifier class <SubClass> extends <SuperClass >{} inherits the implementation through the extends keyword, where SubClass is called a SubClass and Supe RClass is called the parent class or base class. If the access modifier is public, the class is visible throughout the project. If no access modifier is written, the class is only visible to the current package. In java, subclasses can inherit the following content from the parent class: They can inherit the attributes and Methods Modified by public and protected, whether the subclass and the parent class are in the same package, they can inherit the attributes and Methods Modified by the default access modifier, however, the subclass and the parent class must be in the same package and cannot inherit the construction method of the parent class *********************** * *********************************** super Syntax: access parent class constructor: super (parameter) access parent class property/method: super. <parent class property/method> super can only appear in sub-classes (subclass methods and constructor methods), rather than other locations where super is used to access members of the parent class, for example, attributes, methods, and constructor of the parent class. Restrictions on access permissions, if you cannot access private *********************************** through super ********************************** * *********************** instantiate a subclass object: in java, the constructor of a class is always executed in the following two cases: 1. Create an object of the class (instantiate) 2. Create a subclass object of this class (subclass instantiation). Therefore, when instantiating a subclass, it will first execute the constructor of its parent class before executing the constructor of the subclass. When a subclass inherits the parent class, the calling rules of the constructor are as follows: 1. If the constructor of the subclass does not use super, the constructor of the parent class is called, if other constructor methods of the parent class are not displayed through this, the system will first call the non-argument constructor of the parent class by default. In this case, whether to write the super () statement has the same effect. 2. If the super display in the constructor of the subclass calls the constructor of the parent class, the corresponding constructor of the parent class is executed without the constructor of the parent class. 3. If the subclass constructor uses this to display and call other constructor methods, apply the above two rules to the constructor. If there is a multi-level inheritance relationship, when creating a subclass object, the above rules will be applied to the parent class at a higher level multiple times until the non-argument constructor of the Object class of the top-level parent class is executed. **************************************** * ****************** Object class: the Object class is the parent class of all classes. In java, all java classes directly or indirectly inherit java. lang. key code of the Object class: public class Person {}// both methods are equivalent to public class Person extends Object {}********************** * ************************************ part of the Object class toString () returns information about the current object. Returns equals () by string object to compare whether two objects are the same object. If yes, returns trueclone () to generate a copy of the current object, return hashCode () and return the hash code value of the object getClass () to obtain the class information of the current object, returns the Class Object ************************************* * ******************** method rewriting and method Overloading Differences: comparison item location method name parameter table return value access modifier method rewrite the same subclass is the same or its subclass cannot be more rigorous than the parent class method to overload the same class same irrelevant ******* **************************************** * ********** polymorphism: for example, a Pet class has several sub-classes. The Pet class defines the toHospital () method for seeing a doctor, and the sub-classes respectively rewrite the method for seeing a doctor. The key code is class Pet {public void toHospital () {system. out. println! ")}} Class Dog extends Pet {public void toHostipal () {system. out. println ("bird seeing a doctor")} public class Test {public static void main (String [] args) {Pet pet; pet = new Dog (); pet. toHospital (); pet = new Bird (); pet. in the toHospital () ;}} example, the Pet class is generally declared as an abstract method, because its instantiation does not make any sense, and the tohospsp() method is declared as an abstract class. Abstract classes cannot be instantiated. If they are not abstract classes, you must overwrite all abstract methods in the abstract class. abstract modifiers cannot be used together with final modifiers. abstract methods do not have method bodies. private keywords cannot be used to modify abstract methods ******** **************************************** * ********* abstract method: abstract methods do not have a method body. abstract methods must be implemented in the abstract class in the subclass, unless the subclass is an abstract class ************************************ * ********************* upward transformation Syntax: the conversion from a subclass to a parent class is called an upward transformation <parent type> <reference variable name> = new <child type> (). A reference to a parent class points to a subclass object, this is called upward transformation. Automatic type conversion is performed. In this case, when a method called by a variable is referenced by the parent class, the subclass overwrites or inherits the method of the parent class, the method is not a parent class. At this time, variables referenced by the parent class cannot call the unique method of the subclass. Method *************************************** * ****************** syntax for downward Transformation: <child type> <reference variable name >=( <child type>) <reference variable of the parent type> ********************************* * ************************ instanceof OPERATOR: it is used to determine whether an object belongs to a class in the downward transformation process. If it is not converted to a real subclass type, a type conversion exception will occur. Example: Judge the pet type. key code: public class Test {public static void main (String [] args) {Pet pet = new Bird (); pet. toHospital (); if (pet instanceof Dog) {Dog dog = (Dog) pet; dog. catchingFlyDisc ();} else If (pet instanceof Bird) {Bird biird = (Bird) pet; bird. when fly () ;}}}uses instanceof, the object type must have a parent-child relationship with the class specified by the parameter after instanceof, or a compilation error may occur. **************************************** * ****************** Multi-State applications: 1. Form parameters using the parent class as the method: a primary human, in which the method for controlling the animal name is defined. Key code: class Host {public void letCry (Animal animal) {animal. cry () ;}} public class Test {public static void main (String [] args) {Host host = new Host; Animal animal; animal = new Dog (); host. letCry (animal); animal = new Cat (); host. letCry (animal); animal = new Duck (); host. letCry (animal) ;}} 2. Using the parent class as the return value of the method uses the parent class as the return value of the method. This is also the main way to implement and use polymorphism in Java: the host sends three animals, which can be called. Key code: class Host {public Animal donateAnimal (String type) {Animal animal; if (type = "dog") {animal = new Dog ();} else if (type = "cat") {animal = new Cat () ;}else {animal = new Duck () ;}return animal ;}} public class Test {public static void main (String [] args) {Host host = new Host; Animal animal; animal = host. donateAnimal ("dog"); animal. cry (); animal = host. donateAnimal ("cat"); animal. cry ();}}

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.