Object Oriented
In Java, everything is an object. Java is also a high-level object-facing programming language, and object-facing languages have the following characteristics
- (a) Facing objects is a common idea that is more in line with people's thinking habits.
- face-to-face objects can simplify complex business logic and enhance code reusability.
- face-to-face objects have abstraction, encapsulation, inheritance, polymorphism and other characteristics.
Classesโ
class - equivalent to a series of objects abstraction. Concretely like an automatic car, the car's length, width and height are the car's data; the car rides, the horn is the car's method.
Definitionโ
class ClassName{
// body
}
Createโ
ClassName classname = new ClassName();
Constructโ
In Java classes, the constructor method is called once during the creation of an object to ensure that each object is initialized. Constructors are special in that they have no parameter types or return values, the constructor name must be consistent with the class name, and a class can have multiple constructors.
class Apple {
int sum;
String color;
public Apple(){}
public Apple(int sum){}
public Apple(String color){}
public Apple(int sum,String color){}
}
// Create an object
class createApple {
public static void main(String[] args) {
apple apple1 = new Apple();
apple apple2 = new Apple(1);
Apple apple3 = new Apple("red");
apple apple4 = new Apple(2, "color");
}
}
If no constructor method is defined in the class, then the JVM will automatically generate a default constructor method.
Facing objectsโ
Encapsulationโ
Encapsulation is a way of partially wrapping and hiding the implementation details of an abstract functional interface. Encapsulation can be thought of as a protective barrier that prevents the code and data of the class from being randomly accessed by code defined by an external class. Access to the code and data of the class must be controlled by a strict interface.
Dataโ
Data may also be referred to as attributes, and data may be of any type of object, or of a basic data type.
Class A{
int a;
Apple apple;
}
methodsโ
Methods (functions) are used to simplify code, facilitate maintenance, repeat calls, modular programming and improve development efficiency by encapsulating the implementation of multiple lines of code.
Modifier Return value type Method name (parameter type Parameter name) {
...
Method body
...
return return value ;
}
- Modifier : Defines the access type of the method.
- Return value type : Defines the return value type of the method. If the method does not have a return value, the return value type is the keyword void.
- Function name : The actual access name of the calling method.
- Parameter type : Delimits the type of parameter passed when the method is called.
- Parameter name: The actual parameter passed when the method is called. Qualified formal parameters when the method is defined.
- Method Body: Defines the function of the method
Permissionsโ
Instanceโ
public class EncapTest{
private String name;
private String idNum;
private int age;
public int getAge(){
return age;
}
public String getName(){
return name;
}
public String getIdNum(){
return idNum;
}
public void setAge( int newAge){
age = newAge;
}
public void setName(String newName){
name = newName;
}
public void setIdNum( String newId){
idNum = newId;
}
}
Inheritanceโ
Inheritance is when a child class inherits the features and behaviour of the parent class, making the child object (instance) have the instance domain and methods of the parent class, or the child class inherits methods from the parent class, making the child class have the same behaviour as the parent class. This reduces repetitive code, improves maintainability, makes the code more concise and increases the reusability of the code.
! Example of an inheritance diagram
Typeโ
Java does not support multiple inheritance, but does support multiple inheritance.
Featuresโ
- Subclasses have non-private properties and methods of the parent class.
- Subclasses can have their own properties and methods, i.e. they can extend the parent class.
- Subclasses can implement the methods of the parent class in their own way.
- Java inheritance is single inheritance, but multiple inheritance is possible.
- It improves the coupling between classes (the disadvantage of inheritance, the higher the coupling will cause the closer the connection between the code, the less the code independence).
Key wordsโ
- extends: Class inheritance is a single inheritance, where a child class can only have one parent class.
- implements: A disguised way to give java the feature of multiple inheritance, used in the context of classes inheriting from interfaces, which can inherit from multiple interfaces at the same time (with a comma separating the interface from the interface).
- super: The super keyword is used to provide access to the parent class members and to refer to the parent class of the current object.
- this: A reference to itself.
- final: A class defined as not inheritable, i.e. the final class; or used to modify a method, which cannot be overridden by a subclass.
class parent class {
}
class subclass extends parent class {
}
// Single inheritance
public class Animal {
private String name;
private int id;
public Animal(String myName, String myid) {
// initialize property values
}
public void eat() { //concrete implementation of the eat method }
public void sleep() { // concrete implementation of the sleep method }
}
public class Penguin extends Animal{
}
// Inherit multiple interfaces
public interface A {
public void eat();
public void sleep();
}
public interface B {
public void show();
}
public class C implements A,B {
}
// super with this keyword
class Animal {
void eat() {
System.out.println("animal : eat");
}
}
class Dog extends Animal {
void eat() {
System.out.println("dog : eat");
}
void eatTest() {
this.eat(); // this calls its own method
super.eat(); // super calls the parent method
}
}
public class Test {
public static void main(String[] args) {
Animal a = new Animal();
a.eat();
Dog d = new Dog();
d.eatTest();
}
}
// final keyword
final class class name { /* method body*/ }
[public / private / default / protected] final return value type method name() { /* method body */ }
Polymorphismโ
Polymorphism is the ability to have multiple different manifestations or forms of the same behaviour.
Polymorphism is the same interface that performs different operations using different instances, as shown in the figure.
Advantagesโ
- Elimination of coupling between types
- Interchangeability
- Extensibility
- Interfaceability
- Flexibility
- Simplicity
The three conditions necessary for polymorphism to existโ
- Inheritance
- Overwriting
- parent class references pointing to child class objects
How polymorphism is implementedโ
Overriding
Interfaces
Abstract classes and abstract methods
Rewriting and overloadingโ
Overwritingโ
Overriding and overloading, although similar in name, are completely different things. Method overriding is described for subclasses and parent classes between them.
- Methods overridden in a subclass must be consistent with the parent class, including the return value type, method name, and parameter list.
- Methods overridden in a subclass may be identified using the @Override annotation.
- The access rights of the overridden methods in the subclass cannot be lower than the access rights of the methods in the parent class.
class Fruit {
public void eat(){
System.out.printl('eat fruit');
}
}
class Apple extends Fruit{
@Override
public void eat(){
System.out.printl('eat apple');
}
}
Overloadingโ
The same method name has a unique list of parameters, which includes the type, order, and number of parameters that constitute the necessary conditions for method overloading.
- Method names must be the same.
- The list of parameters must be different (different types, order, number, etc.).
- A different return type does not constitute a method overload.
- Overloading is at compile time and it is specifically up to the compiler to determine which method to use.
i.e. the shell remains the same, the core is rewritten!
public class Apple {
int sum;
String color;
public Apple(){}
public Apple(int sum){}
public int getApple(int num){
return 1;
}
public String getApple(String color){
return "color";
}
}
Difference between overriding and overloadingโ
Differences | Overloading Methods | Overriding Methods |
---|---|---|
Parameter list | must be modified | must not be modified |
return type | can be modified | must not be modified |
Exceptions | may be modified | may be reduced or deleted, must not throw new or broader exceptions |
access | may be modified | must not be more restrictive (may be less restrictive) |
Overriding and overloading methods are different manifestations of java polymorphism. Overriding is a manifestation of polymorphism between parent and child classes, and overloading can be understood as a concrete manifestation of polymorphism.
- method overriding is the existence of a method in a subclass with the same name, the same number of parameters and the same type, and the same return value as the method of the parent class, is called overriding.
- method overloading is a class that defines multiple methods with the same name, but with different numbers of arguments or the same number of arguments but different types and orders, is called method overloading (Overloading).
- Method overloading is a manifestation of polymorphism in a class, while method overloading is a manifestation of polymorphism in a subclass and a parent class.
-!
Abstractionโ
In object-oriented concepts, all objects are depicted by classes, but conversely, not all classes are used to depict objects. If a class does not contain enough information to depict a concrete object, such a class is an abstract class.
Since abstract classes cannot instantiate objects, abstract classes must be inherited in order to be used. It is also for this reason that the decision to design an abstract class is usually made during the design phase.
The parent class contains the common methods of a collection of subclasses, but because the parent class itself is abstract, these methods cannot be used. Abstract classes in Java represent an inheritance relationship, where a class can only inherit from one abstract class, whereas a class can implement multiple interfaces.
- Abstract classes cannot be instantiated (an easy mistake for beginners) and if they are, an error will be reported and the compilation will not pass. Only non-abstract subclasses of an abstract class can create objects.
- An abstract class does not necessarily contain abstract methods, but a class with abstract methods must be an abstract class.
- Abstract methods in abstract classes are only declarations and do not contain a method body, i.e. they do not give the concrete implementation of the method, i.e. the concrete function of the method.
- Constructed methods and class methods (methods modified with static) cannot be declared as abstract methods.
- A subclass of an abstract class must give the concrete implementation of the abstract method in the abstract class, unless the subclass is also an abstract class.
Abstract classesโ
// abstract class
public abstract class Employee {
private String name;
private String address;
private int number;
public Employee(String name, String address, int number) {
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.address = address; this.number = number;
}
public double computePay() {
System.out.println("Inside Employee computePay");
return 0.0;
}
public void mailCheck() {
System.out.println("Mailing a check to " + this.name
+ " " + this.address);
}
public String toString() {
return name + " " + address + " " + number;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public void setAddress(String newAddress) {
address = newAddress;
}
public int getNumber() {
return number;
}
}
// Inheritance abstract class
public class Salary extends Employee {
private double salary; //Annual salary
public Salary(String name, String address, int number, double salary) {
super(name, address, number);
setSalary(salary);
}
public void mailCheck() {
System.out.println("Within mailCheck of Salary class");
System.out.println("Mailing check to " + getName()
+ " with salary " + salary);
}
public double getSalary() {
return salary;
}
public void setSalary(double newSalary) {
if(newSalary >= 0.0) {
salary = newSalary;
}
}
public double computePay() {
System.out.println("Computing salary pay for " + getName());
return salary/52;
}
}
// instantiate the Salary object
public class AbstractDemo {
public static void main(String [] args) {
Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);
System.out.println("Call mailCheck using Salary reference --");
s.mailCheck();
System.out.println("\n Call mailCheck using Employee reference --");
e.mailCheck();
}
}
Abstract methodsโ
If you want to design a class that contains a special member method whose concrete implementation is determined by its subclasses, then you can declare the method as an abstract method in the parent class. Also the abstract method must adhere to the following conventions.
- If a class contains an abstract method, then the class must be an abstract class.
- Any subclass must either override the abstract method of the parent class or declare itself to be an abstract class.
// abstract methods
public abstract class Employee {
private String name;
private String address;
private int number;
/*
The Abstract keyword can also be used to declare abstract methods, which contain only a method name and no method body.
The abstract method is not defined and the method name is directly followed by a semicolon instead of brackets.
*/
public abstract double computePay();
// The rest of the code
}
Interfacesโ
An interface, in the JAVA programming language, is an abstract type, a collection of abstract methods, and is usually declared as an interface. A class inherits the abstract methods of an interface by way of inheritance from the interface.
Interfaces are not classes and are written in a similar way to classes, but they are different concepts. A class describes the properties and methods of an object. An interface contains the methods to be implemented by the class.
Interfaces cannot be instantiated, but they can be implemented. A class that implements an interface must implement all the methods described within the interface, otherwise it must be declared as an abstract class.
Featuresโ
- Each method in the interface is also implicitly abstract, and the methods in the interface are implicitly specified as public abstract (only public abstract, any other modifier will report an error).
- Interfaces can contain variables, but the variables in the interface are implicitly specified as public static final variables (and can only be public, any other modifier will result in a compilation error).
- The methods in an interface cannot be implemented in the interface, they can only be implemented by the class that implements the interface.
Interfaces are the same as classes
- An interface can have more than one method.
- Interface files are saved in files ending in .java, using the interface name for the filename.
- The interface bytecode file is stored in a file ending in .class.
- The corresponding bytecode file for the interface must be in a directory structure that matches the package name.
Interfaces differ from classes
- Interfaces cannot be used to instantiate objects.
- Interfaces do not have constructor methods.
- All methods in an interface must be abstract methods.
- Interfaces cannot contain member variables, except for static and final variables.
- Interfaces are not inherited by classes, but have to be implemented by them.
- Interfaces support multiple inheritance.
// Interface declaration
[visibility] interface interface name [extends other interface names] {
// Declare variables
// abstract methods
}
// Interface definition
interface Animal {
public void eat();
public void travel();
}
// Interface implementation
... ...implementations interface name [, other interface names, other interface names... , ...] ...
// Inherited examples
public class MammalInt implements Animal{
public void eat(){
System.out.println("Mammal eats");
}
public void travel(){
System.out.println("Mammal travels");
}
public int noOfLegs(){
return 0;
}
public static void main(String args[]){
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
When overriding methods declared in an interface, the following rules need to be observed.
- A class cannot throw a mandatory exception when implementing a method of an interface, it can only throw that mandatory exception in the interface, or in an abstract class that inherits from the interface.
- Classes should maintain consistent method names when overriding methods, and should maintain the same or compatible return value types.
- If the class implementing the interface is an abstract class, then it is not necessary to implement the methods of the interface.
There are also some rules to be observed when implementing interfaces.
- A class can implement more than one interface at a time.
- A class can only inherit from one class, but can implement more than one interface.
- An interface can inherit from another interface, which is more similar to inheritance between classes.
Multiple inheritanceโ
In Java, multiple inheritance of classes is not legal, but multiple inheritance of interfaces is allowed.
The extends keyword is used only once in multiple inheritance of interfaces, followed by the inherited interface. This is shown as follows.
public interface Hockey extends Sports, Event
Packagesโ
To better organise classes, Java provides the package mechanism, which is used to distinguish the namespace of class names.
A package (package) can be defined as a set of interconnected types (classes, interfaces, enumerations and annotations), providing access protection and namespace management for these types.
- package: Defining packages
package pkg1[.pkg2[.pkg3...]];
// Define
// The path is net/java/util/Something.java
package net.java.util;
public class Something{
...
}
- import: import package
import package1[.package2...]. (classname|*);
// define
package payroll;
public class Boss {
public void payEmployee(Employee e) {
e.mailCheck();
}
}
// wildcard
import payroll.*;
// Introduce the Employee class
import payroll.
What it doesโ
organize classes or interfaces with similar or related functions in the same package, so that they can be easily found and used. 2.
Like folders, packages are stored in a tree directory. The names of classes in the same package are different, and the names of classes in different packages can be the same. When classes with the same class name in two different packages are called at the same time, the package name should be added to distinguish them. Thus, packages avoid name conflicts. 3.
packages also restrict access to classes in a package to those classes that have package access.
Java uses packages as a mechanism to prevent naming conflicts, access control, provide search and locate classes, interfaces, enumerations, annotations, etc.
// Add an interface to the animals package
/* filename: animal.java */
package animals;
interface Animal {
public void eat();
public void travel();
}
package animals;
/* filename : MammalInt.java */
public class MammalInt implements Animal{
public void eat(){
System.out.println("Mammal eats");
}
public void travel(){
System.out.println("Mammal travels");
}
public int noOfLegs(){
return 0;
}
public static void main(String args[]){
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}