JAVA_Basis - 4. 3 object-oriented

1 exception

1.1 Concept:

When the program is running, there is a problem that causes the program to not run normally. The exception in Java refers to the class used to encapsulate the error message that causes the program to not run normally. The composition structure is: type + prompt + line number

1.2 Classification:

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-7jutgTKq-1600301445765)(/img/bVbOJlB)]

Throwable: The parent class of any exception class in Java, representing the common attributes of all exception classes.
Error: (uncheckable exception, no mandatory handling required) refers to a serious problem that cannot be handled by the system in the program.
Exception: (exception can be checked and must be dealt with) means that the program has an abnormal problem that the system can handle.
RuntimeException: Refers to the runtime exception, the program can choose to capture and handle it, or not to handle it.
IOException: Refers to non-runtime exceptions, such exceptions must be handled.

1.3 Exception handling

Encountered an exception in the program, there are usually two ways to deal with it: catch and throw up

1.3.1 Catch exception:

try-catch
try{
    需要捕获的异常代码
}catch(异常类型 异常名字){
    处理方式
}
try-catch-finally
try{

    需要捕获的异常代码
}catch(异常类型 异常名字){
    处理方式
}finally{
    代码块(用于回收资源)
}
Case

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-rXgXcf0U-1600301445769)(/img/bVbOME0)]

	package com.mtingcat.javabasis.object.exception;
	
	import java.util.Scanner;
	
	/**
	 * 测试异常
	 * @author MTing
	 *
	 */
	public class DomeException {
		public static void main(String[] args) {
			
			System.out.println("Input your number:");
			/**
			 * 把可能发生异常的代码放到try代码块里面,一旦
			 * 发生异常就会执行catch中的代码。
			 */
			try {
				@SuppressWarnings("resource")
				int a = new Scanner(System.in).nextInt();
				@SuppressWarnings("resource")
				int b = new Scanner(System.in).nextInt();
				System.out.println("a / b = " + a/b);
			} catch (Exception e) {	
				System.out.println("Input error");
			}
			System.out.println("end");
		}
	
	}

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-Zya4hV5B-1600301445774)(/img/bVbOMFE)]

	package com.mtingcat.javabasis.object.exception;
	
	import java.util.Scanner;
	
	/**
	 * 测试异常
	 * @author MTing
	 *
	 */
	public class DomeException {
		public static void main(String[] args) {
			
			System.out.println("Input your number:");
			/**
			 * 把可能发生异常的代码放到try代码块里面,一旦
			 * 发生异常就会执行catch中的代码。
			 */
			try {
				@SuppressWarnings("resource")
				int a = new Scanner(System.in).nextInt();
				@SuppressWarnings("resource")
				int b = new Scanner(System.in).nextInt();
				System.out.println("a / b = " + a/b);
			} catch (Exception e) {	
				System.out.println("Input error");
			}finally {  //用于回收资源
				System.out.println("finally");
			}
			System.out.println("end");
		}
	
	}

2 Access control character

Used to control the access scope of a class or members of a class.
public: public access rights, members or classes modified by this keyword can be accessed by all other classes.
protected: subclass access rights, members or classes modified by this keyword can be accessed by classes in the same package, or by subclasses in different packages.
default: package access permissions: members or classes modified by this keyword (no access modification keyword) can be accessed by other classes under the same package.
private: The current class access authority. The members or classes modified by this keyword can only be accessed inside the current class.

class package Subclass Any class
public
protected
default
private

3 abstract class

3.1 Concept

Java can define a method without a method body, and the method is specifically implemented by its subclasses. The method without a method body is called an abstract method, and a class containing abstract methods is called an abstract class. An abstract class can be understood as a special class with only method declarations and no method bodies. The abstract class is for inheritance. Single inheritance means that there can be multiple subclasses in a parent class, but a subclass can only have one parent class. The abstract method in the abstract class is so that different behaviors of the subclass can be performed by different subclasses when inheriting the abstract class. Realize separately.

修饰符 abstract 返回值 方法名(参数列表);

3.2 Features

① Implemented through the java keyword abstract
② Methods or classes can be modified
③ There can be no abstract methods in an abstract class (implemented by subclasses)
④ If there are abstract methods in the class, then the class must be defined as an abstract class
⑤ The subclass inherits After the abstract class, either it is still an abstract class, or all abstract methods are rewritten.
⑥ It is mostly used in polymorphism.
⑦ Abstract classes cannot be instantiated.

3.3 Case

3.1 Design ideas:

① Extract the common attributes and methods of all sub-categories into the parent category-extract the common features.
② All sub-categories have the same behavior and are designed in different methods.
③ All subclasses behave differently and are designed as abstract methods.

3.2 Rules

① Abstract classes also have construction methods, but they cannot be instantiated by themselves.
② There can be both variables and constants.
③ In an abstract class, there can be both ordinary methods and abstract methods.

Abstract class
package com.mtingcat.javabasis.abstract11;
/**
 * 抽象类
 * @author MTing
 *
 */
public abstract class abstractAnimals {
	//抽象类中的普通属性
	String name;
	//抽象类中的抽象方法,一个类中如果有抽象方法,那么这个类必须是抽象类,子类中必须重写
	public abstract String eat();
	public abstract String sleep();
	//抽象类中的普通方法
	public String do01(){
		return "抽象类中的普通方法do01()";
	}

}


Subclass
package com.mtingcat.javabasis.abstract11;

public class extendsAnimals extends abstractAnimals{
	
	String sex;
	int age;
	public String run(){
		return "子类添加的方法run()";
	}
	@Override
	public String eat() {
		return "重写了抽象类抽象方法eat()";
	}

	@Override
	public String sleep() {
		return "重写了抽象类抽象方法sleep()";
	}

}

Ordinary

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-8XqnzHzk-1600301445777)(/img/bVbOMNE)]

package com.mtingcat.javabasis.abstract11;

public class Cat {
	public static void main(String[] args) {
		extendsAnimals mtingCat = new extendsAnimals();
		System.out.println(mtingCat.eat());
		System.out.println(mtingCat.sleep());
		System.out.println(mtingCat.do01());
		mtingCat.name = "MTingCat";
		mtingCat.age = 10;
		mtingCat.sex = "boy";
		System.out.println(mtingCat.name+","+mtingCat.age+","+mtingCat.sex);
	}

}

3.4 The meaning of abstract classes

① Encapsulates all the methods and behaviors of the subclass to improve the usability of the code.
② Provide a unified modeling method for sub-categories-upward modeling.
③ It can contain abstract methods to provide a unified entry for subclasses. The specific implementation of subclasses is different, but the entry is the same.

4 member inner class

Set the class in the class, the outer class is called Outer outer class, and the inner class is called Inner inner class.
The inner class usually only serves the outer class and has no external visibility.
Inner class objects usually need to be created in outer classes
The inner class can directly access the members of the outer class (including private ones), and the inner class has an implicit reference to the outer class name of the outer class object that created it. this.

5 Anonymous inner class

If you want to create an object of a class (derived class), and the object is created only once, then the class does not need to be named, and it is called an anonymous inner class.
Access outside variables in the inner class, the variable jdk1.7 (included) must be final before

6 port

6.1 Overview of the interface

Since multiple inheritance is not allowed in ava, if you want to implement the functions of multiple classes, you can implement multiple interfaces.
Java interfaces and Java abstract classes represent abstract types, which are the concrete manifestations of the abstract layer we need to propose. OOP object-oriented programming, if you want to increase the reuse rate of the program, increase the maintainability and scalability of the program, it must be interface-oriented programming, abstract-oriented programming, correctly using interfaces, abstract classes, these are too useful Abstract type as the top level of the Java structure.

6.2 The form of the interface

interface 接口名 {
    代码...
}

6.3 Features of the interface

① Interface is a kind of specification, which breaks through the phenomenon of java single inheritance and is an extension of abstract classes.
② Create through the interface keyword, and implement the subclass through the implements keyword.
③ Only constants and abstract methods can be included in the interface.
③ The interface cannot be instantiated, and the interface and the interface can be realized or inherited.
⑤ The interface needs to be implemented/inherited, and the implementation class/subclass must rewrite the abstract method in the interface to realize the interface.
⑥ A class can have multiple interfaces. The interfaces are separated by commas. If they are inherited and implemented, they should be inherited first and then implemented.
⑦ The interface improves the function expansion of the program and reduces the coupling.

6.4 Case

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-oFJ35ilK-1600301445781)(/img/bVbOUeb)]

package com.mtingcat.javabasis.interface10;
/**
 * 关于接口的入门案例
 * @author MTing
 *
 */
public class entryLevelDemo {
	@SuppressWarnings("static-access")
	public static void main(String[] args) {
		S s01 = new S();
		SSS s02 = new SSS();
		s01.name = "Tom";
		s01.id = 01;
		s01.work();
		System.out.println(s01.study());
		System.out.println("student:"+s01.name+"id:"+","+s01.id);
		System.out.println(s01.studyPlace+s01.studyGroup);
		System.out.println(s02.input());
		
		
		
	}
}

class SSS extends S implements C,Person {
	
	public String input(){
		return "继承的同时实现";
		
	}
}

class S implements Student,C{
	
	String name;
	Integer id;

	@Override
	public String study() {
		return "实现类重写了接口方法student()";
	}

	@Override
	public void work() {
		System.out.println("实现类重写了接口方法work()");
	}

	@Override
	public void show() {
		// TODO Auto-generated method stub
		
	}
	
}

/**
 * 接口Student继承了接口Person和Behave,体现了接口多继承的特性
 * @author MTing
 *
 */
interface Student extends Person,Behave{
	public static final String studyPlace = "school";
	String studyGroup = "class";
	
}

interface Behave{
	public abstract String study();
	void work();
}


interface Person{	
	public abstract void show();
}
interface C{}


6.5 Usage of the interface

6.5.1 Construction method

There is no construction method in the interface. The default is super() when creating an object of the implementation class, and the default is Object() no-argument construction.


interface Person{	
	public abstract void show();
}

6.5.2 Member variables

There are no member variables in the interface, they are all constants. Therefore, when you define a variable without writing modifiers, public static final will be added by default

interface Student extends Person,Behave{
	public static final String studyPlace = "school";
	String studyGroup = "class";
	
}

6.5.3 Member methods of the interface

The methods in the interface are abstract by default. If you don't specify abstract, it will be filled in automatically.
For example: public abstract void save

interface Behave{
	public abstract String study();
	void work();
}

6.5.4 Complex usage of interfaces

The limitation of single inheritance in Java can be solved through interfaces.
Interfaces can be multiple inherited or implemented, and even multiple implementations can be inherited at the same time.

class SSS extends S implements C,Person {
	
	public String input(){
		return "继承的同时实现";
		
	}
}

interface Student extends Person,Behave{
	public static final String studyPlace = "school";
	String studyGroup = "class";
	
}

6.6 Summary

1 The relationship between class and class: inheritance extends / single inheritance / single root inheritance

– The meaning of inheritance: In order to improve the reusability of the code, reduce the writing of the code and improve the development efficiency.
– The meaning of method rewriting: Without modifying the source code of the parent class, rewrite the business in the child class, and since then use the rewritten function.
– The method declaration of the subclass is required to be the same as the parent class, as long as the method body is changed.
-With inheritance and rewriting, polymorphism is produced. The meaning of polymorphism: In order to unify the calling standard of the program, the standard is the parent class.
– Polymorphism means up-casting/up-styling.
– Significance of downward modeling: rarely used, equivalent to wanting to use the special functions of the subclass, it is not as simple as creating the subclass object directly.
– Class A extends B
– where A and B are both classes, A is a subclass, and B is a parent class. A has all the functions of B (except private and construction methods)
– other knowledge points: this and super, Construction method, various code blocks...

2 Relations between classes and interfaces: implementations / single implementation / multiple implementations

– Class A implements B, C
– where A is the implementation class, B and C are interfaces
– A is required to rewrite all abstract methods in the B and C interfaces, otherwise A is an abstract class
– the interface cannot create objects
– There is no construction method in the interface, there are constants in the interface, and abstract methods in the interface

3 Interface and interface relationship: inheritance extends / single inheritance / multiple inheritance

– The relationship of multiple inheritance of interfaces breaks the limitations of java single inheritance
– interface A extends B, C
– where ABC is an interface, A is a sub-interface, and has all the functions in the B and C interfaces at the same time
– class AImpl implements A
-AImpl is required to rewrite all methods in interface A (all methods including interfaces B and C), otherwise it is an abstract class

4 The difference between interface and abstract class! ! !

– Similarities: Both are abstract layers and cannot be instantiated
– Differences:
– 1. Abstract classes are described by abstract keywords, and interfaces are described by interface
– 2. There is an extends relationship between subclasses and abstract classes, and between the implementation class and the interface There is a relationship between implements
– 3. There can be constructors in abstract classes, and no constructors can appear in interfaces
– 4. There can be variables in abstract classes. No variables in interfaces are static constants
– 5. The syntax for defining constants in interfaces: public static final String NAME="jack", will automatically splice variables public static final
– 6. There can be ordinary methods or abstract methods
in abstract classes, and interfaces are abstract methods – 7. There is a connection between abstract class and subclass Inheritance relationship, and in Java, only single inheritance is supported-
8. The interface breaks through the limitations of java single inheritance, because the interface can be multiple inherited or implemented, and even multiple implementations can be inherited at the same time
-9. Complex usage of interfaces
-multiple Inheritance: interface A extends B, C where A is a sub-interface and has its own and BC functions
-multiple implementations: class AImpl implements M,N,O,P where AImpl is the implementation class, and all abstractions of MNOP need to be rewritten at the same time Method, otherwise it is an abstract class
– multiple implementations while inheriting: class AImpl extends Object implements M,N must be implemented first after inheritance

Guess you like

Origin blog.csdn.net/weixin_43388956/article/details/108634792