Java Learning:
Object-oriented:
- Basic object-oriented concepts:
- Java is an object-oriented programming language, C is a process-oriented programming language, each has its strengths.
-Object-oriented three main features:
- Encapsulation:
Invisible to the outside, you can protect some content in the program.
- Inheritance: Extended functionality.
- Polymorphism: Overloading of methods, polymorphism of objects.
-Class-to-object relationship:
-Definition of class:
class defines a category,
class类名称{ 数据类型 属性; ............ public 返回的数据类型 方法名称(参数1,参数2......){ 程序语句; return 表达式; } }
The name of the class must be capitalized in the first letter!
class Person{//人中有姓名和年龄两个属性 Srting name; //姓名 int age; //年龄 public void tell(){ System.out.pringln("姓名:"+name+"年龄:"+age); } }
Person class Diagram:
The first layer represents the name of the class, and the name of the class requires the first letter to be capitalized;
The second layer represents the definition of a property, defined by the format of the Access property name: property type;
The third layer represents the definition of a method in a class, according to the format definition of the Access permission Method name (): Method return value
-Declaration and use of objects:
- Person per = new person ();
- Declaration object: Person per, stack memory declared, as an array, the array name is stored in the stack memory, only open the stack memory object is not available, must have its heap memory reference to be used.
-
Instantiating an object:
New Person (), opens up space in the heap, and all content is the default value.
A class is a reference data type, and it is known from an array that the reference data type inevitably has a reference relationship to the stack memory-heap memory, and in fact, there must be such a relationship between the class and the object's usage.
-
Use format:
调用属性:对象.属性 调用方法:对象.方法()
There are two ways to do this:
Person per = new Person();per.name = "小明";
Or
Person per = null;per = new Person();per.name = "小明";
Attention:
-
The object is stored in the stack memory, and the property is stored in the heap memory;
-
All the methods in the program are stored in the Global Code area, and the content in this area is shared by all objects;
-
The object must be instantiated before it can be used when the object is used;
-
Instantiating an object does not just mean that it is implemented directly through the new keyword, as long as it has a space for heap memory to point to, it means that the instantiation succeeds.
-
If not instantiated-an empty pointing exception occurs, and in a reference operation, this problem occurs if an object does not have a reference to the heap memory, but instead invokes the property or method in the class.
-
The so-called reference data type, which actually passes the use of heap memory, can define multiple stack memory reference operations for a heap memory space at the same time.
Summarize
- Mastering the relationship between stack and heap memory;
- objects are stored in stack memory, and the content is stored in heap memory
- The transfer of reference between objects, actually passing the use of the heap memory space
- The production of rubbish;
-Object-oriented encapsulation
Encapsulation is the protection of content: to ensure that certain properties or methods are not seen externally.
-Implementation of the package:
- Encapsulated for property: Private Property Type property name
- Encapsulation for method: Private method return value method name (parameter list) {}
-Access the encapsulated content:
The encapsulated property needs to be accessed, and the setter and getter methods need to be written to complete;
eg
private String name; publicvoidSetterName(String n){ //设置姓名 "skye" } publicvoidGetterName(){ return name; }
Attention:
- If there is a problem with the age setting, you should not assign a value to the attribute;
- The test should be added to the setter method, and the content is simply retrieved from the getter method;
- Encapsulation in Java has many forms, private is only the most basic form, but also a more common form;
- Each attribute in a class must be encapsulated;
-Construction methods and anonymous objects
- Concept of construction method and timing of invocation
What is a construction method?
The constructor method is called whenever an object has an instantiation.
To construct a method, define the format:
class 类名称{ 访问权限 类名称(类型1 参数1,类型2 参数2,......){ 程序语句; ....//构造方法没有返回值 }}
Declaration of construction Method:
- The name of the construction method must be the same as the class name;
- The declaration of the construction method cannot have any declaration of the return value type;
- You cannot return a value using return in the constructor method;
-
When declaring an object, do not call the constructor method;
Each class will have a constructor method;
Java's operating mechanism, if a class does not explicitly declare a construction method, it will automatically generate a non-parametric construction method of doing nothing, for the user to use.
The primary purpose of the construction method is to initialize the properties in the class.
-Overloading of construction methods
- The construction method, like the normal method, supports overloaded operations, which can be done as long as the type or number of arguments is different.
Use of Anonymous objects
- Anonymous: No name, in Java if an object is used only once, it is called an anonymous object;
- The so-called anonymous object is a reference to a stack memory that is less than the previous object.
- Anonymous objects only open space in heap memory, and there is no reference to stack memory.
Summarize:
- The definition and usage principles of the construction method:
- Constructor method must be called when an object is instantiated
- There is at least one construction method in each class
- Anonymous object: an instance object that only opens up heap memory
-Class Design Analysis:
- Write down the attributes that the class contains according to the requirements;
- All attributes must be encapsulated (private);
- The attributes after encapsulation must be set up and obtained through setter and getter;
- If necessary, several tectonic methods can be added;
- Then add the corresponding method according to other requirements;
- All of the methods in the class are not output directly, but are given to the northing output.
-String class: (More important)
There are two ways of comparing string:
-= = is used to determine whether the address space is equal, the address value is judged, the address value of the comparison;
-If the content is judged equal or not, then the Equals () method is used to compare;
-Two instantiation methods of the String class
Can be assigned directly in string and new is called to construct the method,
String name = "Skye";
Indicates that the point of a heap memory space is given to the stack memory space;
-Two comparison operations of the String class
-Common methods of String:
Language of the use of documents, for users to list all the classes and related operations and use of the method;
-Strings and character arrays
A string can become an array of characters, as well as a character array to a string.
The following methods are available in the String class:
1. Change the string to a character array: public char[] ToCharArray ()
2. The character array becomes a string: public string (char[] value) and
3. Public String (char[] value,int offset,int count)
-Remove the character from the string at the specified position
The return value of this method must be a char type, public char charAt (int index)
public class StringAPIDemo{public ststic void main(String args[]){ String str1 = "hello"; System.out.pringln(str1.charAt(3)); }}
-The conversion of a string to a byte array:
A byte array (a byte array), which is commonly used in IO operations.
-
string into byte array: public byte[] GetBytes ()
-
To change a byte array to a string:
-
Change all byte arrays to String:public String (byte[] bytes)
-
Change a partial byte array to String:public String (byte[] bytes,int offset,int length)
-Gets the length of a string: public int Length ()
public class StringAPIDemo{ public ststic void main(String args[]){ String str1 = "hello skye"; System.out.pringln("\""+str1+"\"的长度为:”str1.length()); } }
Attention:
- You can use the array name in the array. length, and in the operation of the string be sure to remember to use (): string. Length ();
-Finds whether the specified string exists:
- Find from scratch: public int indexOf (String str)
-
Find from specified position: public int indexOf (int ch,int fromIndex)
- Find the return value of the method is a string position, if found to return the position of the string, if not found, he will return 1;
-Remove Spaces:
- If the information is entered by the user, there may be spaces, you need to remove the left and right side of the space, but the space between the strings can not be removed
-Character interception:
Takes a portion of the content from a specified string,
How to use:
-
Intercept from the specified position to the end position: public String substring (int beginindex)
-
Intercepts the specified range of strings: public string substring (int beginindex, int endIndex)
-Split string:
You need to split a string by the specified string: public string[] Split (string regex)
-Uppercase and lowercase conversions:
Convert to uppercase: public String touppercase ()
Convert to lowercase: public String tolowercase ()
-Determines whether to start or end with the specified string:
The public boolean startsWith (string prefix) tests whether this string starts with the specified suffix.
The public boolean endsWith (string suffix) tests whether this string ends with the specified suffix.
-Case-insensitive comparison:
equals can only be compared to strings that are case-consistent.
The public boolean equalsignorecase (string anotherstring) compares this string to another string, regardless of case. If the length of the two string is the same, and the corresponding character Fudusian (ignoring case), the two strings are considered equal. Of
-Reference Pass-the This keyword
- Represents a property in a class:
- Use this to invoke the constructor method:
-
Use this to represent the current object:
Current object: The object that is currently calling the method.
-Java Collection
Role: Storing objects, sometimes containers.
- Array: Defect-type single, fixed length, unable to change the true number of objects in the array cannot be known.
-
Collections: variable-capacity arrays, java.util.collection– interfaces, representing collections
The list interface is sequential and can be repeated
The set interface is not sequential and cannot be duplicated
The map interface is not a sub-interface of the collection, the name value pair, save 2 objects at a time, the preceding object is a key, the following object is value, based on key to get value. Key cannot be duplicated and value can be repeated.
Diagram of the class:
1. Adding objects to the collection
collection c1 = new ArryList();//
- Boolean Add (E) – adds the specified element to the end of the list (optional action).
- A Boolean indicates whether the join was successful.
C1.add ("Hello");
C1.add (New Integer (1));
2. Join all objects in a collection to another collection
collection c2 = new ArryList();
3. Clear all objects in the collection
void Clear ()
4. Compare whether the specified object is contained in the collection
Boolean contains (Object o)
5. Compare all of the contents of a collection that contain another collection
Boolean Containsall (Collection
Packagecom. Skye;Import Java. Util. ArrayList;Import Java. Util. Collection;Import Java. Util. Iterator; / * * Save 10 Student grades with a collection and output the results of the failure. */public class Studentscore {public static void main (string[] args) {Collection score = new ArrayList ();Score. Add( One);Score. Add( -);Score. Add( the);Score. Add( the);Score. Add( the);Score. Add( -);Score. Add( -);Score. Add( -);Score. Add( -);Score. Add( the);Iterators to traverse the collection Iterator it = Score. Iterator();while (it. Hasnext()) {Integer i = (integer) it. Next();if (i< -) {System. out. println(i+"");} } } }
-List
Arrylist– is implemented using arrays,
Characteristics:
- Access elements quickly, change the collection efficiency low (increase, delete, insert more)
- Access by sequence is much, and if you change the contents of the collection less, you choose to use the class
- Use the list collection most often
-LinkedList
Characteristics:
- Modify collection content efficiency, (increase, delete, insert), High resource utilization
- Low efficiency based on sequence access;
- Modify operations frequently, depending on the sequence query operation, choose to use the class
-Vector
-
Old list, thread safe, low efficiency, slow
public class collectiondemo{
Public ststic void Main (String args[]) {
List collection (ordered repeatable)
List List = new LinkedList ();
//向List 集合中添加对象,对象的顺序按照添加的顺序//序列从0开始list.add("hello");list.add("world");list.add("hello");//2.可以为新添加的对象指定添加的位置list.add(1,"hehe");//3.根据对象的序列获取对象System.out.println(list.get(1));//4.返回此列表中第一次出现的指定元素的索引System.out.println(list.IndexOf("hello"));//5.替换list集合的对象list.set()1,"haha";System.out.println(list.get(1));System.out.println(list.get(2));//6.返回列表中指定的 fromIndex(包括 )和 toIndex(不包括)之间的部分视图List newList = list.subList(0,3);System.out.println(newList.size());Iterator it = list.iterator();while(it.hasNext()){ Systom.out.println(it.next()); }}}
Collections Class – A tool class
Collection of tool classes-tool classes: The methods are static statically.
Use:
-
Reverse (List List): Reverses the order of the elements in the list
-
Sort (List List): Sorts the specified List collection elements in ascending order based on the natural ordering of the elements
Arrange according to the natural order of the objects (you can also customize the order)
Collections.sort (list);
It.list.iterator ();
while (IT)
-
Object Max (Collection): Returns the largest element in a given set, based on the natural order of the element
-
void copy (List dest,list src): Copy content from SRC to dest
Practice:
Package com.skye1;/ * * 1. An example of a breeder feeding an animal is an object-oriented idea in Java, the use of an interface (abstract class) *///1. Animal interface--Interface interface Animal{ Public voidEat (food);}//First animal--dog class Dog implements Animal{@Override Public voidEat (food food) {System.out.println ("Dog Bites"+food.getname ()); }}//second animal--Cat class Cat implements Animal{@Override Public voidEat (food food) {System.out.println ("Cat eat"+food.getname ()); }}//2. Food Abstraction Class-- abstractAbstract class food { protectedString name; PublicString GetName () {returnName } Public voidSetName (String name) { This. name = name; }}//First food--fish class Fish extends food { PublicFish (String name) {Super(); This. name = name; }}//second food--Bone class Bone extends food { PublicBone (String name) {Super(); This. name = name; }}//4. Breeder Class-- class feeder{ //There is a method of feeding Public Static voidFeed (Animal animal,food food) {animal.eat (food); }}//5. Test class-Breeder feeding animal Public class testfeeder { Public Static voidMain (string[] args) {Feeder feeder =NewFeeder (); Animal Animal =NewDog (); Food food =NewBone ("Bones");//Feed the dog meat bonesFeeder.feed (Animal,food); Animal =NewCat (); Food =NewFish ("Fish"); Feeder.feed (animal, food);//Feeding cats to fish}}
Java Object-oriented