Classes and Objects in Java

Classes and Objects in Java (3)

package

  1. The package must be the first line of code executable in the program
  2. A package statement can have only one sentence
  3. package naming requires all characters to be lowercase and no special characters to be included
  4. A package can have multiple layers, each with a. Separate, for example: package china.hubei.wuhan; (China is a folder, hubei is a folder under china, and wuhan is a folder under hubei
  5. Do not remove the semicolon after the package statement.
  6. The path of the package conforms to the definition of the system module developed, such as production-to-production, material-to-material, and base-to-base classes.
  7. If a package is not used when defining a class, java assumes that the class we define is in the default package.

encapsulation

Advantage

  1. Good packaging reduces coupling
  2. The structure inside the class can be modified freely
  3. Membership variables can be more precisely controlled
  4. Hide information for details

Permission modifier

When we define member variables in a class, we specify the type of a variable, in addition to the modifier section, which gives the standard format for defining member variables:

// Define Variables
[Modifier] Variable Type Variable Name;
[Modifier] Variable Type Variable Name = initial value;

Permission Relationship Correspondence Table

[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-fGplFNmz-16258974195) (C:UsersWang Guangtao Desktop Permission Table.png)]

  • private: private permissions, accessible only in defined classes, not instances created in other classes
  • Default: The same package has access, which is the default when no permission modifier is declared, allowing access to other classes in the same package
  • protected: protected permissions that allow access to subclasses with inheritance relationships
  • Public: public permissions, allowing access to any class

How to Package

  1. Modify the visibility of attributes to restrict access to attributes (typically restricted to private)

    public class Person {
        private String name;
        private int age;
    }
    

    In this code, the name and age properties are set to private, accessible only to this class, not to any other class, so the information is hidden

  2. Provide public method access to each value property

    That is, to create a pair of assignment methods for accessing private properties

    public class Person{
        private String name;
        private int age;
    
        public int getAge(){
          return age;
        }
    
        public String getName(){
          return name;
        }
    
        public void setAge(int age){
          this.age = age;
        }
    
        public void setName(String name){
          this.name = name;
        }
    }
    

    The this keyword is used to resolve conflicts between instance variables (private String name) and local variables (name variable in setName(String name)) with the same name

inherit

Inheritance is a cornerstone of object-oriented programming because it allows the creation of hierarchical classes

Inheritance is the inheritance by a child of the characteristics and behavior of the parent class, so that the child class object has the instance domain and method of the parent class, or that the child inherits the method from the parent class, so that the child class has the same behavior as the parent class

For example:

  1. Rabbits and sheep are herbivores, lions and leopards are carnivores
  2. Herbivores and carnivores are also animals

Although both herbivores and carnivores are animals, there are differences in their attributes and behavior, so the subclass will have the general characteristics of the parent and will have its own characteristics.

grammar

Using the extends keyword in Java can declare that one class inherits from another

class Parent {
}

class Child extends Parent {
}

Why use inheritance

If we need to develop animals, including penguins and mice, the requirements are as follows:

  1. Penguin: attribute (name, id), method (eat, sleep, self-introduction)
  2. Mouse: attribute (name, id), method (eat, sleep, self-introduction)

There are a lot of duplicates in the code of the two classes, if only once

Join us to have more specific animal classes, don't you want to write to death, the result is large and bloated code, and low maintainability (maintainability is mainly in the later stage when you need to modify, you need to modify a lot of code, which is prone to errors)

So to fundamentally solve the problem with these two pieces of code, you need to inherit and extract the same parts of the two pieces of code to form a parent class

Define a parent class

public class Animal { 
    private String name;  
    private int id; 

    public Animal(String myName, int myid) { 
        name = myName; 
        id = myid;
    } 

    public void eat(){ 
        System.out.println(name+"I am eating"); 
    }

    public void sleep(){
        System.out.println(name+"Sleeping");
    }

    public void introduction() { 
        System.out.println("Hello everyone! I am"         + id + "Number" + name + "."); 
    } 

Animal classes can be used as a parent class, and after penguins and mice inherit this class, they have attributes and methods within the parent class. Subclasses have no duplicate code, are more maintainable, have simpler code, and improve code reuse (reusability is mainly used multiple times without having to write the same code multiple times)

With Animal classes and inheritance mechanisms, we can rewrite penguins and mice

Penguins

public class Penguin extends Animal { 
    public Penguin(String myName, int myid) { 
        super(myName, myid); 
    } 
}

Mouse

public class Mouse extends Animal { 
    public Mouse(String myName, int myid) { 
        super(myName, myid); 
    } 
}

Inheritance Features

  1. Subclasses have non-private ly owned properties of the parent class, methods
  2. Subclasses can have their own properties and methods, that is, they can extend the parent
  3. Subclasses can implement parent's methods in their own way
  4. Java inheritance is single inheritance, but can be multiple inheritance, single inheritance is a subclass can only inherit a parent class, multiple inheritance is, for example, class A inherits class B, class B inherits class C, so according to the relationship, class C is the parent class of class B, class B is the parent class of class A
  5. Increased coupling between classes (inheritance disadvantage, high coupling causes code to connect)

super and this keywords

The super keyword in Java is used to access parent class members and to reference the parent of the current object
this keyword points to its own reference

class Animal{
 void eat(){
 System.out.print("animal: eat");
 }
  void eatTest(){
  this.eat();//Call your own method
  super.eat();//Call method of parent class
  }
}

public class Test{
	public static void main(Sting[] args ){
	Animal a = new Animal();
	a.eat();
	Dog d = new Dog();
	d.eatTest();
	}
}

The compiled output is as follows

animal : eat
dog : eat
animal : eat

final keyword

Effect:

  • Clockest class (eunuch class) when used to modify a class that can be defined as inheritable
  • This method cannot be overridden when modifying it

Modifier class

final class Class name{/*Class Body*/}

Modification Method

public final Return value type method name(){/*Method Body*/}

Instance variables can also be defined as final, and variables defined as final cannot be modified
Methods declared as final classes are automatically declared final, but variables after the instance are not final

constructor

In Java, a subclass cannot inherit the constructor (constructor or constructor) of its parent class.

If the constructor of the parent class has parameters, the constructor of the parent class must be explicitly invoked through the super keyword in the construction of the child class with an appropriate list of parameters

If parameterless construction exists in the parent class, it is not necessary to call the parent class constructor with super in the constructor of the subclass. If the super keyword is not used, the parameterless constructor of the parent class is automatically called

class SuperClass {
  private int n;
  SuperClass(){
    System.out.println("SuperClass()");
  }
  SuperClass(int n) {
    System.out.println("SuperClass(int n)");
    this.n = n;
  }
}
class SubClass extends SuperClass{
  private int n;

  SubClass(){
    super(300);
    System.out.println("SubClass");
  }  

  public SubClass(int n){
    System.out.println("SubClass(int n):"+n);
    this.n = n;
  }
}
public class TestSuperSub{
  public static void main (String args[]){
    SubClass sc = new SubClass();
    SubClass sc2 = new SubClass(200); 
  }
}

Compile and run the Java code above with the following output

SuperClass(int n)
SubClass
SuperClass()
SubClass(int n):200

Keywords: Java

Added by jolly on Thu, 20 Jan 2022 04:29:45 +0200