The Way to Learn JavaSE Texts: [Object-Oriented-----------]

Keywords: Java Attribute

Catalog

Chapter 1: Inheritance (Extexnds)

1.1 What is inheritance?Effect?

Inheritance: The direct use of one object's properties and methods by another
The role of inheritance:
Basic function: Subclasses inherit the parent class and code can be reused.
Primary (important) role: Because of the inheritance relationship, later method overrides and polymorphic mechanisms are available.

2.1 Inherit related attributes

    Class B inherits Class A, which is called superclass, parent class and base class.
	Class B is called subclass, derived class, extension class.
		class A{}
		class B extends A{}
		We usually chat about parent and child classes.
		superclass parent
		Subclass subclass

	(2) Inheritance in java only supports single inheritance, not multiple inheritance, and multi-inheritance is supported in C++.
	This is also a simple aspect of java, in other words, it is not allowed to write code like this in java:
		class B extends A,C{} This is an error.

	(3) Although multi-inheritance is not supported in java, it sometimes has the effect of indirect inheritance.
	For example, class C extends B, class B extends A, that is, C directly inherits B,
	In fact, C also inherits A indirectly.

	(4) It is stipulated in java that subclasses inherit from the parent class and can inherit all but the construction methods.
	However, private properties cannot be accessed directly in subclasses.(Private modifier in parent cannot be in child class
	Direct access.It can be accessed indirectly.)

	Classes in java that do not show any inheritance classes inherit Object classes by default, which are 
	The root class (ancestor class) provided by the java language, that is, an object is inherent 
	All the features in the Object type.

	Inheritance also has some drawbacks, such as: CreditAccount class inherits Account class causing it to
	There is a very high degree of coupling between them, and the CreditAccount class is immediately affected when the Account class changes

When can I use inheritance?
It can be clearly described using the "is a" relationship.

3.1 Method Override (OverRide)

What is method override?
When a subclass inherits a parent class, the inherited method does not meet the needs of the subclass, which overrides the method.
Override the inherited method and execute the overridden method.

The method overrides the conditions that are met:

  1. The two classes are inheritance relationships.
  2. The overridden method and the previous method have the same return value type, the same method name, the same parameter list
  3. Access cannot be lower, it can only be higher.
  4. The overridden method cannot throw more exceptions than the previous method.

Matters needing attention:

  1. Method overrides are for methods only, not properties.
  2. Private methods cannot be overwritten
  3. Construction method cannot override
  4. Method overrides are for instance methods only, and static methods are meaningless.

Code demonstration:

/**
 * Parents: Animals
 */
class Animal{
    private String name;
    //Parameterless construction method
    public Animal() {

    }
	//Parametric construction method
    public Animal(String name) {
        this.name = name;
    }
    //Animals have a way to eat
    public void eat(){

    }
}
/**
 * Cats inherit animals Cats are animals
 */
class Cat extends Animal{
	//Parameterless construction method
    public Cat(){

    }
    //Cats override the parent eat() method!
    public void eat(){
        System.out.println("Cats eat cat food!");
    }

}
/**
 * Dogs inherit animals Dogs are animals
 */
class Dog extends Animal{
	//Parameterless construction method
    public Dog(){

    }
    //Dogs override the parent eat() method!
    public void eat(){
        System.out.println("Dogs eat dog food!!");
    }
}

/**
 1. Test Class
 */
public class Demo {
    public static void main(String[] args) {
       //Create cat object
        Cat cat=new Cat();
        //Cats eat
        cat.eat();
       //Create Dog Object
        Dog dog=new Dog();
        //Dogs eat
        dog.eat();
    }
}

Chapter II: Polymorphism

1.1 What is polymorphism?

Many forms, many states, compile and run in two different states.
	Compile-time is called static binding.
	Runtime is called dynamic binding.
	Animal a = new Cat();
	//When compiling, the compiler finds that the type of a is Animal, so the compiler goes to the Animal class to find the move() method
	//Found, bound, compiled through.But when it runs it has to do with the actual objects in the underlying heap memory
	//The method associated with Real Objects in Heap Memory is automatically called when it is actually executed.
	a.move();
	Typical code for polymorphism: A reference to a parent type points to an object of a subtype.

2.1 Basic Grammar

The concepts of upward and downward transition:

	Upward Transition: Child --->Parent (upcasting)
		Also known as automatic type conversion: Animal a = new Cat();

	Downcasting
		Also known as cast: Cat c = (Cat)a; a cast character needs to be added.
	When does the downward transition take place?
			A method specific to a subclass object needs to be called or executed.
			A downward transition is required before it can be invoked.
	Is there a risk of a downward transition?
			ClassCastException is prone to occur
	How can I avoid this risk?
		    The instanceof operator, which dynamically determines which object a reference points to during the run of a program
			Is it a type or not.
			Get into the habit of using the instanceof operator to make judgments before you transition down.
	
	Whether it's an upward or downward transition, there must first be an inheritance relationship between them so that the compiler will not fail.

Code demonstration:

public class OverrideTest05{
	public static void main(String[] args){
		// Can static methods be invoked using Reference?Yes?
		// Although invoked by reference, it is not related to the object.
		Animal a = new Cat(); //polymorphic
		// Static methods are independent of objects.
		// Although invoked using Reference..But when it actually runs:Animal.doSome()
		a.doSome();

	}
}

class Animal{
	// Static method of parent class
	public static void doSome(){
		System.out.println("Animal Of doSome Method Execution!");
	}
}

class Cat extends Animal{
	// Attempt to override the static method of the parent class among subclasses
	public static void doSome(){
		System.out.println("Cat Of doSome Method Execution!");
	}
}

3.1 instanceof operator

When a type is transformed downward, instanceof must be used for judgment.
Emphasize:

  1. Dynamic judgment of reference pointing to object type at run time
  2. Syntax: Reference to instanceof type
  3. The result of the operation is either true or false
  4. Assuming C instanceof Cat is true, the C reference to the heap memory Java object is a Cat, and the False description is not a Cat

Code demonstration:

/**
 * Parents: Animals
 */
class Animal{

    public Animal() {

    }
    //Animals have a way to eat
    public void eat(){

    }
}
/**
 * Cats inherit animals Cats are animals
 */
class Cat extends Animal {
    public Cat() {

    }
    //Cats override the parent eat() method!

    public void eat() {
        System.out.println("Cats eat cat food!");
    }

    public void run(){
        System.out.println("Cats are walking catwalk");
    }

}
/**
 * Dogs inherit animals Dogs are animals
 */
class Dog extends Animal{

    public Dog(){

    }
    //Dogs override the parent eat() method!
    public void eat(){
        System.out.println("Dogs eat dog food!!");
    }
    public void run(){
        System.out.println("Dog jumping wall!1");
    }
}
/**
 * Test Class
 */
public class Demo {
    public static void main(String[] args) {
        //Downward transition: parent calls child-specific methods.
        Animal animal=new Cat();
        Animal animal1=new Dog();
        //You must use instanceof for judgment
        if(animal instanceof Cat) {
            Cat c=(Cat) animal;
            c.run();//Subclass Specific
        }else if (animal1 instanceof Dog){
            Dog d=(Dog) animal1;
            d.run();//Subclass Specific
        }

    }
}

4.1 super keyword

  1. super can appear in instance and construction methods.
  2. The syntax for super is:'super.','super()'
  3. super cannot be used in static methods.,
  4. Sup. can be omitted in most cases.
  5. Sup() can only appear on the first line of a construction method and invokes the construction method in the "parent class" through the current construction method to initialize the parent type characteristics when creating subclass objects.
  6. super() denotes a construction method that calls a parent class through a subclass object
  7. When the first line of a parameterless construction method has neither this() nor super(), there is a super() by default.
  8. this() coexists with super() and is only on the first line. The parent construction method must execute

When can't super be omitted?
If the parent and child classes have the same attributes, you want to access the characteristics of the parent in the child class.
Code demonstration:

//book
public class Book {
//Title
		String name;
//Construction method
		public Book(){
		super();
		}
	public Book(String name){
		super();
		this.name = name;
	}
 }
//Paper books
public class PaperBook extends Book {
//Construction method
		public PaperBook(){
			super();
		}
		public PaperBook(String name){
			super();
			this.name = name;
		}
//Print Book Name
		public void printName(){
			System.out.println("this.name->Title: " + this.name);
			System.out.println("super.name->Title: " + super.name);
		}
 }
public class BookTest {
	public static void main(String[] args) {
		PaperBook book1 = new PaperBook("Zero Basics Java volume I");
		book1.printName();
	}
 }



Discover from above memory structure diagramThis.nameandSuper.nameThey are essentially the same block of memory, so their output is exactly the same.
What if I add a name attribute to the subclass?

//Paper books
public class PaperBook extends Book {
		String name; //A name attribute is also defined in the subclass
//Construction method
		public PaperBook(){
			super();
		}
		public PaperBook(String name){
			super();
			this.name = name;//ThereThis.name Name representing subclass
		}
//Print Book Name
		public void printName(){
		System.out.println("this.name->Title: " + this.name);
		System.out.println("super.name->Title: " + super.name);
		}
}


The construction method of the parent Book is given to theSuper.nameAssign null, subclass PaperBook's construction method gives when executedThis.nameAssigning "Zero Basics Java Volume I" results in two of the current objects because a variable name with a duplicate name is defined in the subclass PaperBookName, one inherited from the parent and one of your own, must be used if you want to access the name inherited from the parent at this timeSuper.name, when accessing name directly orThis.nameBoth represent access to the current object's own name.

That's all for today's sharing!!!~

Learn together, program happily, welcome to chat with the city lions!!!~

Posted by benz862 on Fri, 26 Jun 2020 17:57:47 -0700