JavaDay13 Abstract classes, interfaces, polymorphisms

tags :

  • java Foundation

flag: blue

@toc

JavaDay13 Abstract classes, interfaces, polymorphisms

I. abstract abstract classes

  • [Demand]
    Require inheritance from subclasses of this class, [force] rewrite these skills and methods, report errors without writing, and elevate business logic problems to grammatical problems, error precedence

  • [Solution]
    Abstract modifies the keywords of abstract classes and abstract methods

  • [Notes]

  1. If a method is modified with abstract, then the method cannot have a method body, which is called the method declaration.
    If a method is modified with abstract, [subclasses that inherit this class must override this method]

  2. If there is a method of abstract modification in a class, then the class must be abstract modification
    The type Hero mus t be an abstract class to define abstract methods

  3. An abstract class cannot have its own class object
    Because there may be abstract methods in abstract modified Abstract classes, and abstract methods have no method body, do not know what code should be run, and create abstract class objects, there will be such a hidden danger, so [abstract classes are no class objects of their own]

  4. It's okay for a class to be abstracted, but it doesn't contain abstract methods, but do you think it makes sense?
    Grammar is OK, but it has no practical meaning.

[Summary]
If a class inherits an abstract class modified with abstract, it is required that the class must [implement] all abstract methods in the abstract class.

Code Example 1:

abstract class Hero {
	//Membership variables
	int blood;
	int power;

    // In a parent class containing inheritance, two constructions are generally provided: one is empty
	public Hero() {}
	
	public Hero(int blood, int power) {
		this.blood = blood;
		this.power = power;
	}
	
	/*
	 Here, all heroes have three skills, QWE, and the three methods must be rewritten to inherit the Hero subclass.
	 Here you can use abstract to modify these methods
	 */
	abstract public void Q();
	abstract public void W();
	abstract public void E();
	
	public void test() {
		System.out.println("test");
	}
}

abstract class Test {
	public void test() {
		System.out.println("test");
	}
}

/*
	Fizz Classes inherit Hero classes because Hero contains three abstract-modified methods
 	So you need to [implement] these three methods in the Fizz class
 */
class Fizz extends Hero {
	
	//Construction method
	public Fizz() {}
	
	public Fizz(int blood, int power) {
		super(blood, power); //Initialize the member variables of the parent class by calling the constructor of the parent class
	}
	
	//Implementing the Q method implement ations that require subclasses of the parent class to inherit the parent class
	@Override
	public void Q() {
		System.out.println("Naughty Strike");
	}

	//Implementing the W method implement ations of subclasses that require inheritance of the parent class
	@Override
	public void W() {
		System.out.println("Sea Stone Trident");
	}

	//Implementing the E-method implement ations of subclasses that require inheritance from the parent class
	@Override
	public void E() {
		System.out.println("Goblins");
	}	
}

class Caitlyn extends Hero{
	
	public Caitlyn() {}
	
	public Caitlyn(int blood, int power) {
		this.blood = blood;
		this.power = power;
	}

	@Override
	public void Q() {
		System.out.println("Messenger of Peace");
	}
	
	@Override
	public void W() {
		System.out.println("Yodel trap");
	}
	
	@Override
	public void E() {
		System.out.println("90 Caliber rope net");
	}
}

public class Demo1 {
	public static void main(String[] args) {
		Fizz fizz = new Fizz(100, 100);
		
		fizz.Q();
		fizz.W();
		fizz.E();
		fizz.test();
		
		Caitlyn caitlyn = new Caitlyn(100, 100);
		
		caitlyn.Q();
		caitlyn.W();
		caitlyn.E();
		caitlyn.test();
		
		//Hero h = new Hero();
	}
}

The results of program operation are as follows:

Naughty Strike
 Sea Stone Trident
 Goblins
 test
 Messenger of Peace
 Yodel trap
 90 caliber rope net
 test

Code Example 2:

package com.qfedu.a_abstract;

/*
 Demand:
  	Describes a graphic class Shape class that requires all inheritance
  	There must be a method for calculating circumference and area for subclasses of this kind.
  	
  	Implementing shape class
  	Implementing circle-like square triangle inherited from shape class
 */

abstract class Shape {
	abstract float perimeter();
	abstract float square();
}

class MyCircle extends Shape {
	
	private float r;
	private float PI = 3.1415926f;
	
	public MyCircle() {}
	
	public MyCircle(float r) {
		if (r <= 0) {
			this.r = 1;
		} else {
			this.r = r;
		}
	}

	@Override
	public float perimeter() {
		return 2 * r * PI;
	}

	@Override
	public float square() {
		return r * r * PI;
	}	
}

class Rect extends Shape {

	float length;
	float width;
	
	public Rect() {}
	
	public Rect(int length, float width) {
		this.length = length;
		this.width = width;
	}
	
	@Override
	public float perimeter() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public float square() {
		// TODO Auto-generated method stub
		return 0;
	}
	
}

class Triangle extends Shape {
	float l1;
	float l2;
	float l3;
	
	public Triangle() {}
	
	public Triangle(float l1, float l2, float l3) {
		if (l1 < (l2 + l3) && l2 < (l1 + l3) && l3 < (l1 + l2)) {
			this.l1 = l1;
			this.l2 = l2;
			this.l3 = l3;
		} else {
			throw new RuntimeException("Wrong!!!");
		}
	}
	
	
	@Override
	public float perimeter() {
		return l1 + l2 + l3;
	}

	@Override
	public float square() {
		float p = (l1 + l2 + l3) / 2;
		
		return (float) Math.sqrt(p * (p - l1) * (p - l2) * (p - l3));
		
	}
	
}

public class Demo2 {
	public static void main(String[] args) {
		
	}
}

II. Interface

  • [Function]
    Interfaces in the code:
    Expanding the functionality of the current class, or patching it

The keyword interface UI used in the interface: User Interface

  • Format:
Interface interface name{
// Expanded Contents
 Membership variables and membership methods
}

Nomenclature of interface name is big hump nomenclature

[Compliance] Keyword implements for interfaces

  • [Supplementary knowledge]
    The final keyword:
    • The final keyword can be used to modify member variables and local variables. The variables modified with final can not change after assignment.
    • If final modifies a class, it cannot be inherited.
    • final modifies a method that cannot be overridden;

Membership methods in interfaces have no method body

  • [Default attributes in interfaces]

    • 1. The default attribute of member variables in interfaces is public static final modification, which requires direct assignment when defining member variables.
      For example, when defining a standard, the size of the USB interface is determined.
    • 2. The default attribute of the member method in the interface is abstract. Here is the method that requires the class of the interface to be complied with.
      For example, the USB interface specifies the connection mode and hardware requirements.
  • [Notes]

    • 1. Defining methods in interface is an abstract modification method, requiring the class of the interface to implement these methods.
    • 2. In the interface, all the member variables of the definition method are modified with final, only the right of use, not the right of assignment (right of modification).
    • 3. A class can [comply] with more than one interface. Different interfaces are separated by commas, and the implements keyword is used to comply with the interface.

Java is a single inheritance, multi-implementation/compliance language.

interface A {
	//Membership variables
	int num = 10; //[default property] public static final
	//Membership method
	void testA(); //abstract
}

interface B { 
	void testB();
}

//Here you use the implements keyword to follow the interface
public class Demo1 implements A, B {

	@Override
	public void testA() {
		System.out.println("Implementing the required completion in the interface testA Method");
	}

	@Override
	public void testB() {
		System.out.println("Compliance interface B Realization testB Method");
		
	}
	public static void main(String[] args) {
		Demo1 d1 = new Demo1();
		
		d1.testA(); //[Comply with] the interface, and implement the method specified in the interface, call the method
		System.out.println(d1.num); //[Compliance] Interface, using member variables in the interface
		//d1.num = 200; because the default attribute of the member variable defined on the street is public static final 
		//And final modifies variables, where the data can't be changed.
		d1.testB();
	}

	
}

3. Polymorphism

  • The concepts are as follows:
    A reference to a parent class points to an object of a subclass, or a reference to an interface points to an object of an interface class.

  • Attentions in the use of polymorphism:

    1. In polymorphic cases, the reference of the parent class calls the normal member method with the same name as the parent class, and the call is the method of the child class.
    2. In the case of polymorphism, the reference of the parent class calls the ordinary member variable of the same name as the parent class, and the call is the member variable of the parent class.
    3. In polymorphic cases, the reference of the parent class calls the [static] member method of the same name as the parent class, and the [static] member method of the parent class calls, which is of little use.
    4. In the case of polymorphism, references to parent classes [cannot] call member variables specific to subclasses

IV. Unified Interface

Example code 1: If the required parameter in the method is a class object, it is also possible to pass in the [subclass] object of that class in this parameter.

package lianxi;

/*
A zoo:
Animal
	Monkey
	Tiger
	Snake
	
Now all animals need to be fed.

It was found that there was a way of feeding everything, and the way of feeding was the same.
Summary of the idea: Can you put these methods together?

Think: Can we achieve a way of feeding animals?

Feeding animals, to determine which class to operate on, can only use Animal classes.

It was found that:
	This requires that the incoming object is the method of the Animal class object, and that the subclass object of the incoming Animal can also run without any error or prompt.
	In a method, if the required parameter is a class object, then the [subclass] object of that class can also be passed into the parameter.
	For example:
	eat(Animal a) The method of replacing Animal a with Monkey m is also working.
*/


class Animal {
	int age; 
	
	public Animal() {}
	public Animal(int age) {
		this.age = age;
	}	
	
	public void eat(Animal a) {
		System.out.println(a.getClass() + "Eating"); // getclass denotes getting the class name
	}
	
	public Animal tellMyWhoAreYou(Animal a) {
		System.out.println(a.getClass());
		return a;
	}
}

class Monkey extends Animal {	
}

class Tiger extends Animal {
}

class Snake extends Animal {	
}

public class Demo1 {
	public static void main(String[] args) {
		Monkey m = new Monkey();
		m.eat(m);
	
		Tiger t = new Tiger();
		t.eat(t);
		
		Snake s = new Snake();
		s.eat(s);

        System.out.println("---------------------------------------");
        
		Animal a = new Animal();
		
		a.eat(m); 
		//The requirement here is an Animal class object, but the input is a Monkey class object.
	   //The direct relationship between the Monkey class and the Animal class is that Monkey is a subclass of Animal.
		a.eat(t);
		a.eat(s);

        System.out.println("---------------------------------------");
        
		//The original expression: Animal ma = a.tellMyWhoAreYou(s); 
		//************************ Important**********************************
		Monkey ma = (Monkey) a.tellMyWhoAreYou(m);
		System.out.println(ma);
		
		Snake ms = (Snake) a.tellMyWhoAreYou(s);
		Tiger mt = (Tiger) a.tellMyWhoAreYou(t);
	}
	
}

The results of program operation are as follows:

class lianxi.MonkeyEating
class lianxi.TigerEating
class lianxi.SnakeEating
---------------------------------------
class lianxi.MonkeyEating
class lianxi.TigerEating
class lianxi.SnakeEating
---------------------------------------
class lianxi.Monkey
lianxi.Monkey@2a33fae0
class lianxi.Snake
class lianxi.Tiger

Example code 2: In a method, the parameter format defined is an interface, and the parameter passed in is the object of the interface, no problem.

package com.qfedu.c_duotai;

//Provide a USB interface. All USB devices are required to complete connect() in the USB interface.
interface USB {
	void connect();
}

//U disk complies with USB interface and implements connect method
class UPan implements USB {
	@Override
	public void connect() {
		System.out.println("U Disk Connect Computer, Transfer Data");
	}
}

//The keyboard complies with the USB interface and implements the connect method.
class Keyboard implements USB {
	@Override
	public void connect() {
		System.out.println("Recommend filco Keyboard, with and without tea shafts");
	}
}

class Computer {
	//There's a USB interface on the computer, but it's uncertain what device will use USB, depending on who will connect, but what device will connect.
	//Must [comply] with USB interface
	public void USBConnect(USB usb) {
		usb.connect();
	}
}

public class Demo2 {
	public static void main(String[] args) {
		Computer MBP = new Computer();
		
		//The incoming object is an anonymous U disk object that complies with the USB interface
		MBP.USBConnect(new UPan());
		
		//The incoming keyboard anonymous object is a [compliant] USB interface
		MBP.USBConnect(new Keyboard());
		
		/*
		 The formal parameter defined is an interface, but what is passed in is the class object of the [compliance] interface. 
		 */
	}
}



Example code 3: polymorphism: parent reference points to child class object;

package com.qfedu.c_duotai;

class Father {
	String name; //Membership variables in parent classes
	int weight = 90; //Membership variables with the same name as subclasses
	
	public Father() {}
	 
	public Father(String name) {
		this.name = name;
	}
	
	public void game() {
		System.out.println("Manchester");
	}
	
	public static void work() {
		System.out.println("Mechanical Engineer");
	}
}

class Son extends Father {
	int age = 16; //Subclass's own member variables 
	int weight = 74; // Membership variables with the same name as the parent class
	
	public Son(String name) {
		super(name);
	}
	
	@Override
	public void game() {
		System.out.println("Housten Rocket");
	}
	
	public static void work() {
		System.out.println("Teacher of the Jobi Program Ape");
	}
}

public class Demo3 {
	public static void main(String[] args) {
//		Son s = new Son("David");
//		s.game();
//		s.work();
//		
//		Father f = new Father("Jack");
//		f.game();
//		f.work();
		
		//Parent Class Reference to Objects that Point to Subclasses [Polymorphism]
		Father ftoS = new Son("23333");
		
		ftoS.game();
		
		System.out.println(ftoS.weight);
		
		ftoS.work();
		
//		System.out.println(ftoS.age);
	}
}

The results of program operation are as follows:

Housten Rocket
90
 Mechanical Engineer

Keywords: Attribute Java

Added by ghettopixel on Fri, 23 Aug 2019 14:20:10 +0300