亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
4) Filter valid data" >4) Filter valid data
5) Summary" >5) Summary
1) Inheritance in the program" >1) Inheritance in the program
2) Selection of parent category" >2) Selection of parent category
3) Inheritance" >3) Inheritance
4) Characteristics of inheritance" >4) Characteristics of inheritance
5) Not inheritable" >5) Not inheritable
1) Method rewriting /Override" >1) Method rewriting /Override
2)方法重寫與方法重載的區(qū)別" >2)方法重寫與方法重載的區(qū)別
1)super關(guān)鍵字" >1)super關(guān)鍵字
2)super調(diào)用父類無參構(gòu)造" >2)super調(diào)用父類無參構(gòu)造
3)super調(diào)用父類有參構(gòu)造" >3)super調(diào)用父類有參構(gòu)造
4)this與super" >4)this與super
1)多態(tài)的應(yīng)用" >1)多態(tài)的應(yīng)用
Home Java JavaBase What are the three major characteristics of java

What are the three major characteristics of java

Jan 06, 2023 pm 02:30 PM
java

The three major characteristics of Java are: 1. Encapsulation, which is to hide some information of a class inside the class and not allow direct access by external programs. Instead, the hidden information is realized through the methods provided by the class. Operation and access. 2. Inheritance means that the subclass has all the properties and methods of the parent class, thereby realizing code reuse. 3. Polymorphism means that parent class references point to subclass objects, thus producing multiple forms.

What are the three major characteristics of java

The operating environment of this tutorial: windows7 system, java8 version, DELL G3 computer.

The three major characteristics of Java

The three major characteristics of object-oriented: encapsulation, inheritance, and polymorphism.

Encapsulation:

  • Hides some information of the class inside the class and does not allow direct access by external programs. Instead, the hidden information is operated through the methods provided by the class. and access.

Inheritance:

  • The subclass owns all the properties and methods of the parent class (except for privately modified properties), thus realizing the reuse of implementation code;

Polymorphism:

  • Use the parent class reference to accept object instances of different subclasses. The parent class reference calls the same method, and generates different instances according to the subclass. Different results

1, encapsulation

1) What is encapsulation

Concept: Hide the internal implementation details of the object as much as possible, and control the modification and access permissions of the object.

Access modifier: private (attributes can be modified as private, visible only to this class)

2) Public access method

In the form of access methods, assignment and value acquisition operations are completed.

Problem: Illegal data entry is still not solved!

  • Provide public access methods to ensure normal data entry.
  • Naming specification:
  • Assignment: setXXX() //Use method parameters to achieve value assignment
  • Value: getXXX() //Use method return value to achieve value

3) Example

public static void main(String[] args) {
		int a;
		Num num = new Num();
//		傳入值100
		num.setNum(100);
		System.out.println(num.getNum());
	}
private int a;

//	在調(diào)用get方法時(shí),返回本類a的值
	public int getNum() {
		return a;
	}

//	接受傳入的值100,并賦值給本類的a
	public void setNum(int num) {
		this.a = num;
	}

4) Filter valid data

In the public access method, add logical judgment to filter out illegal data to ensure data security.

5) Summary

The get/set method is the only channel for the outside world to access the private properties of the object. The data can be detected and filtered inside the method. .

2. Inheritance

1) Inheritance in the program

  • Inheritance in a program is a gift or acquisition of characteristics and behaviors between classes.
  • The inheritance relationship between two classes must satisfy the "is a" relationship.

2) Selection of parent category

  • In real life, there are differences between many categories Inheritance relationships all satisfy the "is a" relationship.

  • A dog is an animal, a dog is a living thing, and a dog is a substance.

  • Multiple categories can be used as the parent category of "dog", and the most suitable parent category needs to be selected.

  • The more refined the function, the more overlapping points, and the closer it is to the direct parent class.

  • The rougher the function, the fewer overlapping points, and the closer it is to the Object class. (The concept that everything is an object)

3) Inheritance

Syntax: class subclass extends parent Class { } //When defining a subclass, display the inherited parent class

public class 子類名 extends 父類名{
	
	//代碼塊
	}

Application: After the inheritance relationship is generated, the subclass can use the attributes and methods in the parent class, or define unique properties for the subclass properties and methods.

Benefits: It not only improves the reusability of the code, but also improves the scalability of the code.

4) Characteristics of inheritance

Java is single inheritance. A class can only have one direct parent class, but it can have multi-level inheritance. Properties and methods stack up one level at a time.

5) Not inheritable

Constructor method: The constructor method in a class is only responsible for creating objects of this class and cannot be inherited.

Private modified properties and methods: a type of access modifier, visible only to this class.

When the parent and child classes are not in the same package, the attributes and methods modified by default: a type of access modifier, only visible in the same package.

3. Method rewriting

1) Method rewriting /Override

Method rewriting principle:

  • The method name and parameter list are the same as those of the parent class.
  • The return value type must be the same as the parent class or its subclass
  • The access modifier can be the same as the parent class or wider than the parent class.

Execution of method rewriting:

  • After a subclass overrides a parent class method, the rewritten method of the subclass will be executed first when called.

  • Characteristics of method overriding:

    When a subclass overrides a parent class method, the subclass method will override the parent class method.

    Subclasses override parent class methods, and the access level cannot be stricter than parent class methods.

    The subclass override method name and type are the same as the parent class.

    父類的構(gòu)造方法無法重寫,只能被覆蓋。

示例:

//父類
public class Animal {
//	父類中吃的方法會(huì)輸出“玩玩玩”
	public void play() {
		System.out.println("玩玩玩");
	}

//	父類中睡的方法會(huì)輸出“睡睡睡”
	public void sleep() {
		System.out.println("睡睡睡");
	}

}
/**
 * 狗類繼承 父類
 */
public class Dog extends Animal {

//	進(jìn)行方法重寫,將方法重寫輸出為“狗玩飛碟”
	public void play() {
		System.out.println("狗玩飛碟");
	}
}
public class Test {

	public static void main(String[] args) {
		// 實(shí)例化寵物對象
		Dog d = new Dog();
		d.play();
		d.sleep();
	}

}

運(yùn)行輸出:

What are the three major characteristics of java

2)方法重寫與方法重載的區(qū)別

相同點(diǎn):方法名相同
不同點(diǎn):
重載:參數(shù)列表不同,返回值與訪問修飾符無關(guān)
重寫:參數(shù)列表相同,返回值相同或其子類,訪問修飾符不能比父類更嚴(yán)

4、super關(guān)鍵字

1)super關(guān)鍵字

super關(guān)鍵字可在子類中訪問父類的方法。

  • 使用”super.”的形式訪問父類的方法,進(jìn)而完成在子類中的復(fù)用;
  • 再疊加額外的功能代碼,組成新的功能。

2)super調(diào)用父類無參構(gòu)造

super():表示調(diào)用父類無參構(gòu)造方法。如果沒有顯示書寫,隱式存在于子類構(gòu)造方法的首行。

3)super調(diào)用父類有參構(gòu)造

super():表示調(diào)用父類無參構(gòu)造方法。

super(實(shí)參):表示調(diào)用父類有參構(gòu)造方法。
參構(gòu)造被執(zhí)行

4)this與super

this或super使用在構(gòu)造方法中時(shí),都要求在首行。
當(dāng)子類構(gòu)造中使用了this()或this(實(shí)參),即不可再同時(shí)書寫super()或super(實(shí)參),會(huì)由this()指向構(gòu)造方法完成super()調(diào)用。

class A{
		public A(){
		System.out.println(( "A-無參構(gòu)造"));
		}
		public A(int value) {
		System.out.println(("A-有參構(gòu)造")); 
		}
		}
		class B extends A{
		public B(){
		super();
		System.out.println( "B-無參構(gòu)造");
		}
		public B(int value) {
//		super();這兩貨不能跟同時(shí)存在
		this();
		System.out.println(("B-有參構(gòu)造"));
		}
		}

5、多態(tài)

概念:父類引用指向子類對象,從而產(chǎn)生多種形態(tài)。

二者具有直接或間接的繼承關(guān)系時(shí),父類引用可指向子類對象,即形成多態(tài)。

父類引用僅可調(diào)用父類所聲明的屬性和方法,不可調(diào)用子類獨(dú)有的屬性和方法。

1)多態(tài)的應(yīng)用

方法重載可以解決接收不同對象參數(shù)的問題,但其缺點(diǎn)也比較明顯。

  • 首先,隨著子類的增加,Master類需要繼續(xù)提供大量的方法重載,多次修改并重新編譯源文件。
  • 其次,每一個(gè)feed方法與某一種具體類型形成了密不可分的關(guān)系,耦合太高。

場景一:使用父類作為方法形參實(shí)現(xiàn)多態(tài),使方法參數(shù)的類型更為寬泛。

public class Animal {
//		父類中吃的方法會(huì)輸出“玩玩玩”
	public void play() {
		System.out.println("玩玩玩");
	}

//	父類中睡的方法會(huì)輸出“睡睡睡”
	public void sleep() {
		System.out.println("睡睡睡");
	}

}
/**
 * 狗類繼承 父類
 * 
 * 
 *
 */
public class Dog extends Animal {

//	狗類特有的方法“狗吃狗糧”
	public void eat() {
		System.out.println("狗吃狗糧");
	}

}
public class Test {

	public static void main(String[] args) {
		// 實(shí)例化寵物對象
		Animal d = new Dog();
		d.play();
		d.sleep();
//		The method eat() is undefined for the type Animal
//		對于類型動(dòng)物,eat()方法未定義
//		當(dāng)我們?nèi)フ{(diào)用子類對象的特有方法時(shí),就會(huì)爆出上面的錯(cuò)誤提示
//		如果想要實(shí)現(xiàn)子類特有方法,就必須要強(qiáng)轉(zhuǎn)
//		d.eat();
		((Dog) d).eat();
	}

}

運(yùn)行輸出:

What are the three major characteristics of java

場景二:使用父類作為方法返回值實(shí)現(xiàn)多態(tài),使方法可以返回不同子類對象。

示例:

//動(dòng)物類  父類
public class Animal {
	public void food() {
		System.out.println("...");
	}
}
//用extends關(guān)鍵字,繼承父類屬性
public class Dog extends Animal {

	public void food() {
		System.out.println("狗吃狗糧");
	}

	public void runing() {
		System.out.println("一直跑跑跳跳");
	}
}
//用extends關(guān)鍵字,繼承父類屬性
public class Fish extends Animal {
	public void food() {
		System.out.println("大魚吃小魚,小魚吃蝦米");
	}

	public void swimming() {
		System.out.println("小魚兒,一直游");
	}
}
public class Master {
//	傳入你的動(dòng)物,并去給它喂食
	public void food(Animal animal) {
		System.out.println("喂食");
		animal.food();
	}
}
import java.util.Scanner;

public class Shopping {
//	你沒有動(dòng)物,所以animal為空
	Animal animal = null;

//	判斷你要購買的寵物,并返回寵物類(狗、魚)
	public Animal shopping(int a) {
		if (a == 1) {
			animal = new Dog();
		} else if (a == 2) {
			animal = new Fish();
		}
//		this.animal=animal;
		return animal;
	}

	public void showMenu() {
		Scanner input = new Scanner(System.in);
		System.out.println("歡迎來到一只寵物寵物店");
		System.out.println("請選擇喜歡的寵物:");
		System.out.println("1.狗 2.魚 ");
		int a = input.nextInt();
		Animal animal = shopping(a);
		Master mm = new Master();
		mm.food(animal);
//		用instanceof判斷你買的是狗還是魚。
//		狗就執(zhí)行狗的屬性和方法,魚就執(zhí)行魚的屬性和方法
		if (animal instanceof Dog) {
			Dog d = (Dog) animal;
			d.runing();
		} else if (animal instanceof Fish) {
			Fish f = (Fish) animal;
			f.swimming();
		}

	}
}
//測試類
public class text {
	public static void main(String[] args) {
		Shopping shop = new Shopping();
		shop.showMenu();
	}
}

運(yùn)行結(jié)果:

What are the three major characteristics of java

2)多態(tài)的靜態(tài)和動(dòng)態(tài)實(shí)現(xiàn)

動(dòng)態(tài)綁定:即為重寫/覆蓋,方法的重寫

動(dòng)態(tài)綁定也叫后期綁定,在運(yùn)行時(shí),虛擬機(jī)根據(jù)具體對象實(shí)例的類型進(jìn)行綁定,或者說是只有對象在虛擬機(jī)中運(yùn)行創(chuàng)建了之后,才能確定方法屬于哪一個(gè)對象實(shí)例的

  • 根據(jù)實(shí)際對象是什么,就去找相應(yīng)對象方法去執(zhí)行。
  • 動(dòng)態(tài)綁定是在運(yùn)行時(shí)才會(huì)執(zhí)行(例如重寫的方法)。

靜態(tài)綁定:即為重載,方法的重載

一個(gè)方法的參數(shù)在編譯階段常被靜態(tài)地綁定,它是根據(jù)參數(shù)列表的不同來區(qū)分不同的函數(shù),通過編輯之后會(huì)變成兩個(gè)不同的函數(shù)

  • 根據(jù)類型找相應(yīng)的屬性或者靜態(tài)變量。
  • 靜態(tài)綁定是在編譯時(shí)執(zhí)行(如成員變量,靜態(tài)方法)。

更多編程相關(guān)知識(shí),請?jiān)L問:編程教學(xué)??!

The above is the detailed content of What are the three major characteristics of java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode settings.json location VSCode settings.json location Aug 01, 2025 am 06:12 AM

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

python itertools combinations example python itertools combinations example Jul 31, 2025 am 09:53 AM

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

Mastering Dependency Injection in Java with Spring and Guice Mastering Dependency Injection in Java with Spring and Guice Aug 01, 2025 am 05:53 AM

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

python pytest fixture example python pytest fixture example Jul 31, 2025 am 09:35 AM

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

A Guide to Java Flight Recorder (JFR) and Mission Control A Guide to Java Flight Recorder (JFR) and Mission Control Jul 31, 2025 am 04:42 AM

JavaFlightRecorder(JFR)andJavaMissionControl(JMC)providedeep,low-overheadinsightsintoJavaapplicationperformance.1.JFRcollectsruntimedatalikeGCbehavior,threadactivity,CPUusage,andcustomeventswithlessthan2%overhead,writingittoa.jfrfile.2.EnableJFRatsta

Best Practices for Writing Maintainable Java Code Best Practices for Writing Maintainable Java Code Jul 31, 2025 am 06:21 AM

Follow naming specifications to make the code as easy to read as prose; 2. The method should be small and focused, and a single responsibility is easy to test and reuse; 3. Write meaningful comments to explain "why", rather than obvious operations; 4. Prioritize immutability and packaging to prevent external accidental modifications; 5. Exceptions should be properly handled without ignoring and providing clear information; 6. Unit tests should be clearly named and cover key paths; 7. Reasonable use of modern Java features such as var and Stream to improve readability; 8. Organization of package structures layered by functions to improve project navigation efficiency - these practices jointly ensure that Java code is maintained for a long time.

Laravel error and exception handling Laravel error and exception handling Jul 31, 2025 am 11:57 AM

Laravel's error and exception handling mechanism is based on the PHP exception system and Symfony component, and is managed uniformly by the App\Exceptions\Handler class. 1. Record exceptions through the report() method, such as integrating Sentry and other monitoring services; 2. Convert exceptions into HTTP responses through the render() method, supporting custom JSON or page jumps; 3. You can create custom exception classes such as PaymentFailedException and define their response format; 4. Automatically handle verification exception ValidationException, and manually adjust the error response structure; 5. Decide whether to display details based on the APP_DEBUG configuration.

See all articles