Detailed explanation of java object-oriented – Part 1

1、 Classes and objects

1. Composition of class

2. Properties

Member variable vs local variable

3. Method

Provide the implementation of a function

    public void eat(){//方法体}
    public String getName(){}
    public void setName(String n){}
    //格式:权限修饰符 返回值类型(void:无返回值/具体的返回值) 方法名(形参){}

4. Landing rule 1 of the idea of object-oriented programming:

5. Class initialization memory parsing: structure of memory partition

6. Everything is an object

7. Examples

/*
 * 4. 对象数组题目:
定义类Student,包含三个属性:学号number(int),年级state(int),成绩score(int)。
 创建20个学生对象,学号为1到20,年级和成绩都由随机数确定。
问题一:打印出3年级(state值为3)的学生信息。
问题二:使用冒泡排序按学生成绩排序,并遍历所有学生信息

提示:
1) 生成随机数:Math.random(),返回值类型double;  
2) 四舍五入取整:Math.round(double d),返回值类型long。
 * 
 * 
 *  // 两位数的,随机数  10 - 99
  公式:【a,b】 :   Math.random()*(b-a+1)+a   再强转数据类型。
 * 
 */
public class StudentTest {
	public static void main(String[] args) {

		// 声明Student类型的数组
		Student[] stu = new Student[20];

		for (int i = 0; i < stu.length; i++) {
			// 给数组元素赋值
			stu[i] = new Student();
			stu[i].number = i + 1;
			// [1,6]
			stu[i].state = (int) (Math.random() * (6 - 1 + 1) + 1);
			// [0,100]
			stu[i].score = (int) (Math.random() * (100 - 0 + 1));
		}

		StudentTest test = new Studenttest();
		
		// 问题1
		test.searchState(stu,3);
		System.out.println("------------------------");
		//
		// 问题2
		test.sort(stu);
		test.print(stu);
		
	}

	
	// 遍历学生数组
	public void print(Student[] stu) {
		for (int i = 0; i < stu.length; i++) {
			System.out.println(stu[i].info());
		}
	}

	/**
	 * 
	 * @Description  查找指定年纪的学生
	 * @author MD
	 * @date 2020年7月6日下午12:02:56
	 * @param stu 查找的数组
	 * @param state 指定的年纪
	 */
	public void searchState(Student[] stu,int state) {
		for (int i = 0; i < stu.length; i++) {
			if (stu[i].state == 3)
				System.out.println(stu[i].info());
		}
	}
	
	
	public void sort(Student[] stu) {
		for (int i = 0; i < stu.length - 1; i++) {
			for (int j = 0; j < stu.length - i - 1; j++) {
				if (stu[j].score <= stu[j + 1].score) {
					// 注意,这里交换的不是成绩而是对象
					Student temp = stu[j];
					stu[j] = stu[j + 1];
					stu[j + 1] = temp;
				}
			}
		}
	}

}

class Student {
	int number;
	int state;
	int score;

	public String info() {
		return "学号:" + number + " 年级:" + state + " 分数:" + score;
	}

}

2、 Method overload

Requirements: * the method name must be the same in the same class * the parameter list of the method is different (① the number of parameters is different ② the parameter type is different). Supplement: the overload of the method has nothing to do with the return value type of the method!

//如下的四个方法构成重载
//定义两个int型变量的和
public int getSum(int i,int j){
    return i + j;
}
//定义三个int型变量的和
public int getSum(int i,int j,int k){
    return i + j + k;
}
//定义两个double型数据的和
public double getSum(double d1,double d2){
    return d1 + d2;
}

//定义三个double型数组的和
public void getSum(double d1,double d2,double d3){
    System.out.println(d1 + d2 + d3);
}
//不能与如上的几个方法构成重载
//  public int getSum1(int i,int k){
//      return i + j + k;
//  }
//  public void getSum(int i,int k){
//      System.out.println(i + j + k);
//  }


//以下的两个方法构成重载。
public void method1(int i,String str){
    
}
public void method1(String str1,int j){
    
}

3、 Method of variable number formal parameters

//如下四个方法构成重载
    //在类中一旦定义了重载的可变个数的形参的方法以后,如下的两个方法可以省略
//  public void sayHello(){
//      System.out.println("Hello World!");
//  }
//  public void sayHello(String str1){
//      System.out.println("hello " + str1);
//  }
    //可变个数的形参的方法
    public void sayHello(String ... args){
        for(int i = 0;i < args.length;i++){
            System.out.println(args[i] + "$");
        }
        //System.out.println("=====");
    }
    
    public void sayHello(int i,String ... args){
    //public void sayHello(String ... args,int i){
        System.out.println(i);
        
        for(int j = 0;j < args.length;j++){
            System.out.println(args[j] + "$");
        }
    }
    
    public void sayHello1(String[] args){
        for(int i = 0;i < args.length;i++){
            System.out.println(args[i]);
        }
    }
    

4、 Java value passing

1. Example 1

public static void main(String[] args) {
    TestArgsTransfer tt = new TestArgsTransfer();
    
    int i = 10;
    int j = 5;
    System.out.println("i:" + i + " j:" + j);//i : 10  j : 5
    
//      //交换变量i与j的值
//      int temp = i;
//      i = j;
//      j = temp;
    tt.swap(i,j);//将i的值传递给m,j的值传递给n
    
    
    System.out.println("i:" + i + " j:" + j);//i : 10  j : 5
    
}
//定义一个方法,交换两个变量的值
public void swap(int m,int n){
    int temp = m;
    m = n;
    n = temp;
    System.out.println("m:" + m + " n:" + n);

}

2. Example 2

public class TestArgsTransfer1 {
    public static void main(String[] args) {
        TestArgsTransfer1 tt = new TestArgsTransfer1();
        DataSwap ds = new DataSwap();
        
        System.out.println("ds.i:" + ds.i + " ds.j:" + ds.j);
        
        tt.swap(ds);
        System.out.println(ds);
        
        System.out.println("ds.i:" + ds.i + " ds.j:" + ds.j);
        
    }
    //交换元素的值
    public void swap(DataSwap d){
        int temp = d.i;
        d.i = d.j;
        d.j = temp;
        System.out.println(d);//打印引用变量d的值
    }
}

class DataSwap{
    int i = 10;
    int j = 5;
}

3. Example 3

package com.atguigu.exer;

import java.io.PrintStream;

public class Test {

	public static void main(String[] args) {
		int a = 10;
		int b = 10;
		method(a,b);
		System.out.println("a="+a);
		System.out.println("b="+b);
	}
	
//	public static void method(int a,int b) {
//		a = a * 10;
//		b = b * 20;
//		System.out.println(a);
//		System.out.println(b);
//		System.exit(0);
//	}
	public static void method(int a,int b) {
		PrintStream ps = new PrintStream(System.out) {
			public void println(String x){
				if("a=10".equals(x)) {
					x = "a=100";
				}else if("b=10".equals(x)) {
					x = "b=200";
				}
				super.println(x);
			}
		};
		
		System.setOut(ps);
	}

	
}

4. Example 4

What is the output?

public class Test1 {

	public static void main(String[] args) {
		int[] arr = new int[] {1,2,3};
		System.out.println(arr); //地址值
		
		char[] arr1 = new char[] {'a','b','c'};
		System.out.println(arr1); //abc
	}
}

5、 Object oriented feature 1: Encapsulation

1. Constructor

Role of constructor: ① create object ② assign value to the attribute of the created object

2. This keyword

public class TestPerson {
    public static void main(String[] args) {
        Person p1 = new Person();
        System.out.println(p1.getName() + ":" + p1.getAge());
        
        Person p2 = new Person("BB",23);
        int temp = p2.compare(p1);
        System.out.println(temp);
    }
}
class Person{
    
    private String name;
    private int age;
    
    public Person(){
        this.name = "AA";
        this.age = 1;
    }
    
    public Person(String name){
        this(); // 先调用空参数的
        this.name = name;
    }
    public Person(String name,int age){
        this(name);
        this.age = age;
    }
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public void eat(){
        System.out.println("eating");
    }
    public void sleep(){
        System.out.println("sleeping");
        this.eat();
    }
    //比较当前对象与形参的对象的age谁大。
    public int compare(Person p){
        if(this.age > p.age)
            return 1;
        else if(this.age < p.age)
            return -1;
        else
            return 0;
    }
    
}

3. package/import

Package: declare the package where the source file is located, which is written in the first line of the program. Import:

/import java.util.Scanner;
//import java.util.Date;
//import java.util.List;
//import java.util.ArrayList;
import java.lang.reflect.Field;
import java.util.*;
import static java.lang.System.*;
public class TestPackageImport {
    public static void main(String[] args) {
        out.println("helloworld");
        Scanner s = new Scanner(system.in);
        s.next();
        
        Date d = new Date();
        List list = new ArrayList();
        
        java.sql.Date d1 = new java.sql.Date(522535114234L);
        
        Field f = null;
    }
}

6、 Object oriented feature 2: Inheritance

1. Override orverwrite vs overload

class Cirlce{
   //求圆的面积
    public double findArea(){
   
    } 

}

class Cylinder extends Circle{
      //求圆柱的表面积
      public double findArea(){
      }
}

3. The whole process of subclass object instantiation

No matter which constructor is used to create a subclass object, you need to ensure that the parent class is initialized first

Purpose: when a subclass inherits from the parent class, it inherits all the properties and methods in the parent class. Therefore, the subclass must know how the parent class initializes the object

public class TestDog {
    public static void main(String[] args) {
        Dog d = new Dog();
        d.setAge(10);
        d.setName("小明");
        d.setHostName("花花");

        System.out.println("name:" + d.getName() + " age:" + d.getAge()
                + "hostName:" + d.getHostName());
        
        System.out.println(d.toString());
    }
}

// 生物
class Creator {
    private int age;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Creator() {
        super();
        System.out.println("this is Creator's constructor");
    }

}

// 动物类
class Animal extends Creator {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Animal() {
        super();
        System.out.println("this is Animal's constructor");
    }

}

// 狗
class Dog extends Animal {
    private String hostName;

    public String getHostName() {
        return hostName;
    }

    public void setHostName(String hostName) {
        this.hostName = hostName;
    }

    public Dog() {
        super();
        System.out.println("this is Dog's constructor");
    }
}

7、 Object oriented feature 3: polymorphism

1. Expression of polymorphism:

① Method overloading and rewriting ② polymorphism of subclass objects

2. Premise of use:

① There should be inheritance relationship ② there should be method rewriting

3. Format

When compiling, it is considered that P is of type person, so it can only execute the structure only in person, that is, the unique structure in man cannot be called, and the polymorphism of subclass objects is not used for attributes.

Calling method: see the left for compilation and the right for operation

Properties: compile and run both on the left

package com.atguigu.java;

public class AnimalTest {

	public static void main(String[] args) {
		
		AnimalTest test = new Animaltest();
		// 多态性的体现
		test.func(new Dag());
		test.func(new Cat());
	}

	public void func(Animal an) {  // Animal an = new Dag();
		an.eat();
		an.shot();
	}
	
	
//	public void func(Dag dag) {
//		dag.eat();
//		dag.shot();
//	}
	
}

class Animal{
	public void eat() {
		System.out.println("动物:吃食物");
	}
	
	public void shot() {
		System.out.println("动物:叫");
	}
}

class Dag extends Animal{
	public void eat() {
		System.out.println("狗吃肉");
	}
	
	public void shot() {
		System.out.println("汪!汪");
	}
}

class Cat extends Animal{
	public void eat() {
		System.out.println("猫吃鱼");
	}
	
	public void shot() {
		System.out.println("喵!喵");
	}
}

4. On downward transformation

With the polymorphism of the object, the memory actually loads the properties and methods unique to the subclass. However, because the variable is declared as the parent type, only the properties and methods declared in the parent class can be called during compilation. The properties and methods unique to the subclass cannot be called, so there is a downward transformation

if (p1 instanceof Woman) {
            System.out.println("hello!");
            Woman w1 = (Woman) p1;
            w1.shopping();
  }

   if (p1 instanceof Man) {
        Man m1 = (Man) p1;
         m1.entertainment();
  }

5. Is polymorphism compiler behavior or runtime behavior

Runtime behavior

package com.atguigu.java5;


import java.util.Random;

//面试题:多态是编译时行为还是运行时行为?
//证明如下:
class Animal  {
 
	protected void eat() {
		System.out.println("animal eat food");
	}
}

class Cat  extends Animal  {
 
	protected void eat() {
		System.out.println("cat eat fish");
	}
}

class Dog  extends Animal  {
 
	public void eat() {
		System.out.println("Dog eat bone");
	}
}

class Sheep  extends Animal  {

	public void eat() {
		System.out.println("Sheep eat grass");
	}
}

public class InterviewTest {

	public static Animal  getInstance(int key) {
		switch (key) {
		case 0:
			return new Cat ();
		case 1:
			return new Dog ();
		default:
			return new Sheep ();
		}
	}

	public static void main(String[] args) {
		int key = new Random().nextInt(3);

		System.out.println(key);

		Animal  animal = getInstance(key);
		
		animal.eat();
	}
}

package com.atguigu.exer;
/*
 * 练习:
 * 1.若子类重写了父类方法,就意味着子类里定义的方法彻底覆盖了父类里的同名方法,
 * 系统将不可能把父类里的方法转移到子类中:编译看左边,运行看右边
 * 
 * 2.对于实例变量则不存在这样的现象,即使子类里定义了与父类完全相同的实例变量,
 * 这个实例变量依然不可能覆盖父类中定义的实例变量:编译运行都看左边
 */
class Base {
	int count = 10;

	public void display() {
		System.out.println(this.count);
	}
}

class Sub extends Base {
	int count = 20;

	public void display() {
		System.out.println(this.count);
	}
}

public class FieldMethodTest {
	public static void main(String[] args) {
		Sub s = new Sub();
		System.out.println(s.count);//20
		s.display();//20
		
		Base b = s;//多态性
		//==:对于引用数据类型来讲,比较的是两个引用数据类型变量的地址值是否相同
		System.out.println(b == s);//true
		System.out.println(b.count);//10
		b.display();//20
	}
}

7. Question 2

package com.atguigu.exer;

//考查多态的笔试题目:
public class InterviewTest1 {

	public static void main(String[] args) {
		Base1 base = new Sub1();
		base.add(1,3); //sub_1

		Sub1 s = (Sub1)base;
		s.add(1,3); //sub_2
	}
}

class Base1 {
	public void add(int a,int... arr) {
		System.out.println("base1");
	}
}

class Sub1 extends Base1 {

	public void add(int a,int[] arr) {
		System.out.println("sub_1");
	}

	public void add(int a,int b,int c) {
		System.out.println("sub_2");
	}

}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>