Chapter 5 advanced JAVA object oriented

Chapter 5 advanced JAVA object oriented


  • inherit
    • Use the extends keyword. Extensions means "extension" in English, and the subclass is the extension of the parent class. If you define a class without calling extends, its parent class is: java.lang.Object
    • There is only one inheritance in Java, not multiple inheritance like C + +
    • There is no multiple inheritance for classes and interfaces in Java
    • The child class inherits the parent class and can get all the properties and methods of the parent class (except the construction method of the parent class), but it is not necessarily directly accessible (for example, the private properties and methods of the parent class)
  • instanceof operator: binary operator, object on the left and class on the right. Returns true when the object is created by the right class or subclass; otherwise, returns false.
package cn.sxt.oo;

public class TestExtends {
	public static void main(String[] args) {
	Student student = new Student("quan",171,"cv");;;
	System.out.println(student instanceof Student);
	System.out.println(student instanceof Person);
	System.out.println(student instanceof Object);

class Person{
	String name;
	int height;
	public void rest(){
		System.out.println("Take a break~");
class Student extends Person{
	String major;
	public Student(String name,int height,String major) { = name;
		this.height = height;
		this.major = major;
	public void study() {
  • override of method

    • By overriding the method of the parent class, the child class can replace the behavior of the parent class with its own behavior
    • "= =": method name and parameter list are the same
    • '≤': return value type and declaration exception type, subclass less than or equal to parent
    • "≥": access permission, subclass greater than or equal to parent
  • The Object class is the root base class of all Java classes, which means that all Java objects have the properties and methods of the Object class

    • The public String toString() method is defined in the Object class, and its return value is of type String. The source code of toString method in Object class is:
    public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    • toString() method override
public class TestObject {
	public static void main(String[] args) {
		TestObject to = new TestObject();
		System.out.println(to.toString());//Equal to previous line
	public String toString() {
		return "test";
  • ==And equals methods
public class TestEquals {
	public static void main(String[] args) {
		Object obj;
		String str;
		User user1= new User(001,"quan","1234");
		User user2= new User(001,"quanquan","1234");
		System.out.println(user1 == user2);  //false
		System.out.println(user1.equals(user2)); //ture(User class overrides equals)
		String str1 = new String("sxt");
		String str2 = new String("sxt");
		System.out.println(str1 == str2);//false
		System.out.println(str1.equals(str2));//True (the String class rewrites equals, and you can press Ctrl and click String to view its source code)
class User {
	int id;
	String name;
	String pwd;
	public User(int id, String name, String pwd) {
		super(); = id; = name;
		this.pwd = pwd;
// Added automatically by the system, optional
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + id;
		return result;
//Right click - > source - > generate hashcode() and equals()
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		User other = (User) obj;
		if (id !=
			return false;
		return true;
  • super keyword

    • Super is a reference to a direct parent object. You can use super to access the methods or properties in the parent class that are covered by the child class.

      Use super to call ordinary methods. Statements have no location restrictions and can be called in subclasses at will.

    • The first sentence of construction method is always: super( ), to call the constructor corresponding to the parent class. Therefore, the process is: first trace up to the Object, and then execute the initialization block and construction method of the class down to the current subclass.

      Note: the static initialization block call order is the same as the construction method call order.

  • encapsulation

    • Private means private. Only your own class can access it
    • default means that there is no modifier, and only classes of the same package can access it
    • protected means that it can be accessed by classes in the same package and subclasses in other packages
    • public means that it can be accessed by all classes in all packages of the project
Modifier Same class Same package Subclass All classes
private *
default * *
protected * * *
public * * * *
  • Packaging details

    • Generally use private access

    • Provide the corresponding get/set methods to access the related properties. These methods are usually decorated with public to provide the assignment and reading operations for the properties. (Note: the get method of boolean variable starts with is!) only the class of get / set method is called JavaBean.

      Right click - > Click source (Alt+Shift+S) - > generate getters and setters

    • In general, other methods in the working class are decorated with public unless it is determined that they are only used for this class.

  • polymorphic

    • Polymorphism is method polymorphism, not attribute polymorphism (polymorphism is independent of attribute)
    • There are three necessary conditions for polymorphism: inheritance, method rewriting, and parent class reference to child class object
    • After a parent class reference points to a child class object, the parent class reference calls the method overridden by the child class, and polymorphism appears
  • Transformation of objects

    • The parent class reference points to the child class object. We call this process upward transformation, which belongs to automatic type transformation
    • The parent class reference variable after upward transformation can only call the method of its compiled type, not the method of its runtime type. At this time, we need to carry out type coercion, which we call downward transformation!
  • final keyword

    • Modifier variable: the variable modified by him cannot be changed. Once the initial value is assigned, it cannot be reassigned.
    • Decorated method: this method cannot be overridden by a subclass. But it can be overloaded!
    • Decorated class: decorated class cannot be inherited. For example: Math, String, etc.

Next, I will introduce a little knowledge of array (Chapter 7), and practice J20 aircraft war game (Chapter 13)


  • Abstract methods and abstract classes

    • Abstract method: a method decorated with abstract. There is no method body, only declaration. It defines a "specification", which tells the subclass to provide concrete implementation for abstract methods
    • Abstract class: a class containing abstract methods is an abstract class. The specification is defined by the abstract method, and then the concrete implementation must be defined for subclass. By abstracting classes, we can strictly restrict the design of subclasses and make them more general
    • Classes with abstract methods can only be defined as abstract classes
    • Abstract class cannot be instantiated, that is, it cannot be instantiated with new
    • Abstract classes can contain properties, methods, and construction methods. But the construction method can't be used for new instance, it can only be used for being called by subclass.
    • Abstract classes can only be used to be inherited, and abstract methods must be implemented by subclasses
  • Interface

    [access modifier] interface name [extends parent 1, parent 2 {
    Constant definition;   
    Method definition;
    • Access modifier: can only be public or default; interface name: same naming mechanism as class name; extensions: interface can inherit more
    • Constant: an attribute in an interface can only be a constant (the name is best capitalized), always: public static final. Not to write.
    • Method: Methods in an interface can only be: public abstract. If omitted, it is also public abstract.
  • JAVA class has no extensions, but JAVA interface has implements

  • Inner class

    • Internal classes can be decorated with public, default, protected, private, and static
    • In Java, inner classes are mainly divided into member inner classes (non static inner classes, static inner classes), anonymous inner classes, and local inner classes
  • Non static inner class (there is no difference between using non static inner class in outer class and using other classes normally)

    • A non static inner class must reside in an outer class object. Therefore, if there is a non static inner class object, there must be a corresponding outer class object. An object that belongs to an external class
    • The non static inner class can directly access the members of the outer class, but the outer class cannot directly access the members of the non static inner class
    • Non static inner classes cannot have static methods, static attributes, and static initialization blocks
    • Static methods and static code blocks of external classes cannot access non static internal classes, including defining variables and creating instances with non static internal classes
public class TestInnerClass {
	public static void main(String[] args) {
		//Create inner class object
		Outer.Inner inner = new Outer().new Inner();;

class Outer {
	private int age = 10;
	class Inner {
		public void show() {
			System.out.println("Member variables of external classes age: "+Outer.this.age);
  • Static inner class
    • When a static inner class object exists, there is not necessarily a corresponding outer class object. Therefore, the instance method of static inner class cannot directly access the instance method of outer class
    • The static inner class is regarded as a static member of the outer class. Therefore, the static members of static inner class can be accessed through "static inner class. Name" in the method of external class, and the instance of static inner class can be accessed through new static inner class ()
  • Anonymous inner class: it is suitable for a class that only needs to be used once. For example: keyboard monitoring operation and so on.
new parent constructor (argument class table) \ implementation interface (){
           //Anonymous inner class body!
  • Local inner class: it is defined inside the method and its scope is limited to this method

  • API document

    • API (Application Programming Interface) is a pre-defined function, which aims to provide the ability of application program and developers to access a set of routines based on a certain software or hardware without accessing the source code or understanding the details of internal working mechanism.
    • The API document is a technical content delivery file that contains instructions on how to use and integrate the API effectively. It is a concise reference manual, which contains all the information needed to use the API. It introduces the functions, classes, return types, parameters, etc. in detail, and the tutorial is the example support.
    • Read online and select SE version
    • Download address
    • Download in Chinese
  • Common methods of String class

public class StringTest1 {
    public static void main(String[] args) {
        String s1 = "core Java";
        String s2 = "Core Java";
        System.out.println(s1.charAt(3));//Extract characters with subscript 3
        System.out.println(s2.length());//Length of string
        System.out.println(s1.equals(s2));//Compare two strings for equality
        System.out.println(s1.equalsIgnoreCase(s2));//Compare two strings (case ignored)
        System.out.println(s1.indexOf("Java"));//Whether Java is included in string s1
        System.out.println(s1.indexOf("apple"));//Does the string s1 contain apple
        String s = s1.replace(' ', '&');//Replace the space in s1 with&
        System.out.println("result is :" + s);
public class StringTest2 {
    public static void main(String[] args) {
        String s = "";
        String s1 = "How are you?";
        System.out.println(s1.startsWith("How"));//Start with How
        System.out.println(s1.endsWith("you"));//End with you or not
        s = s1.substring(4);//Extract substring: from the beginning of subscript 4 to the end of the string
        s = s1.substring(4, 7);//Extract substring: subscript [4, 7) does not include 7
        s = s1.toLowerCase();//Turn lowercase
        s = s1.toUpperCase();//Turn capitalization
        String s2 = "  How old are you!! ";
        s = s2.trim();//Remove spaces at the beginning and end of the string. Note: the space in the middle cannot be removed
        System.out.println(s2);//Because String is immutable, s2 remains unchanged


1, 1. AB 2. A 3. D 4. B 5. ADC

Three. Reference resources

package cn.sxt.oo;

import java.util.Scanner;

public class Test1 {
	public static void main(String[] args) {
		Scanner scanner1 = new Scanner(;
		System.out.print("Enter the radius of the cylinder:");
		float r = scanner1.nextFloat();
		Scanner scanner2 = new Scanner(;
		System.out.print("Enter the height of the cylinder:");
		float h = scanner1.nextFloat();
		Cylinder cylinder = new Cylinder();

class Circle{
	private float radius;
	public float getRadius() {
		return radius;

	public void setRadius(float radius) {
		this.radius = radius;

	public Circle() {
	public Circle(float radius) {
		this.radius = radius;

	public double getArea(float radius) {
		return Math.PI*radius*radius;
	public double getPerimeter(float radius) {
		return 2*Math.PI*radius;
	public void show(float radius,double area ,double perimeter) {
		System.out.println("The radius of the circle is"+radius);
		System.out.println("The circumference of a circle is"+perimeter);
		System.out.println("The area of the circle is"+area);

class Cylinder extends Circle{
	private float hight;
	public float getHight() {
		return hight;

	public void setHight(float hight) {
		this.hight = hight;
	public Cylinder() {
	public double getVolume(float radius) {
		return hight*getArea(radius);
	public void showVolume(double volume) {
		System.out.println("The volume of the cylinder is"+volume);
package cn.sxt.oo;

public class Test2 {
	public static void main(String[] args) {
		TestInstrument testInstrument = new TestInstrument();
		Erhu i = new Erhu();
		testInstrument.test("quanquan", i);

class TestInstrument{ //Test class
	public void test(String name,Instrument i) {
		System.out.println("Musician Name:"+name);
		Musician musician = new Musician();;

class Musician{ //Musicians
	public void play(Instrument i) {

 class Instrument{ //Musical instruments
	 public void makeSound() {

class Erhu extends Instrument{
	public void makeSound() {

class Piano extends Instrument{
	public void makeSound() {

class Violin extends Instrument{
	public void makeSound() {
package cn.sxt.oo;

public class Test3 {
	public static void main(String[] args) {
		YiRen person = new YiRen();
		System.out.println("Hello, I'm Yang Mi");

interface Moive{
	void moive();
interface TvSeries{
	void tvSeries();
interface Sing{
	void sing();

class YiRen implements Moive,TvSeries,Sing{
	public void moive() {
		System.out.println("I can make movies");	
	public void tvSeries() {
		System.out.println("I can play TV");	
	public void sing() {
		System.out.println("I can sing.");	
Published 6 original articles, praised 0 and visited 48
Private letter follow

Tags: Java Attribute REST less

Posted on Mon, 16 Mar 2020 10:52:27 -0400 by c0le