[Java Basics] Detailed Explanation of Object-Oriented Programming (Part 1) Exercises

written in front


        Hello everyone, I am [ Lin-Xiaobai ], a student majoring in software engineering , who likes computer knowledge . I hope everyone can learn and progress together ! I am a college student , and my professional level is limited. If you find any mistakes or deficiencies , please correct me! thank you all! ! !

        If brothers and sisters are interested in my articles, please don't be stingy with your little hands, give more likes and follow ! ❤❤❤ Love you guys! ! !


Table of contents

written in front

[Detailed explanation of object-oriented programming (on) knowledge]

class instantiation

Code

Programming question 1

Programming question 2

Method usage

Method declaration and call

method overloading

write the output

write the output

What is the result of running the following code?

object-oriented

Explanation of the three major characteristics of object-oriented

The difference between the scope public, private, protected, and when it is not written by default

find fault

Garbage collection of Java's memory management (understand)

Interview questions:

constructor

Whether the constructor Constructor can be overridden

Program to create a Box class, define three variables in it to represent the length, width and height of a cube, and define a method to find the volume of the cube. Creates an object that finds the volume of a cube of given dimensions. (provides a parameterless constructor and a parameterized constructor)

define a circle type

Design a Dog class with name, color and age attributes, define a constructor to initialize these attributes, and define an output method show() to display its information.

write a human class

Write a car class:

The result of running the following program is:

About parameter passing

exercise one

exercise two

Exercise three

Exercise four

Exercise five

What is the result of executing the following code

short answer

epilogue


[Detailed explanation of object-oriented programming (on) knowledge]

This article will give you an in-depth understanding of [Java Basics] Object-Oriented Programming (Part 1)①

This article will give you an in-depth understanding of [Java Basics] Object-Oriented Programming (Part 1)②


class instantiation

Code

Write a Student class, including name, gender, age, id, and score attributes, which are String, String, int, int, and double types respectively.

A say method is declared in the class, which returns the String type, and the method return information contains all attribute values.

In the main method of another StudentTest class, create a Student object, access the say method and all attributes, and print out the result of the call.

/*
 * 代码实现
编写一个Student类,包含name、gender、age、id、score属性,分别为String、String、int、int、double类型。
类中声明一个say方法,返回String类型,方法返回信息中包含所有属性值。
在另一个StudentTest类中的main方法中,创建Student对象,并访问say方法和所有属性,并将调用结果打印输出。
 */

public class StudentTest {
	public static void main(String[] args) {
		Student stu = new Student();
		stu.name = "Tom";
		stu.age = 10;
		stu.gender = "man";
		stu.score = 65.5;
		stu.id = 123456;
		String info = stu.say();
		System.out.println(info);
	}
}

public class Student {
	String name;
	String gender;
	int age;
	int id;
	double score;
	
	public String say(){
		return "姓名是:" + name + ", 性别是:" + gender + ", 年龄是:" 
				+ age + ", id是:" + id + "分数是:" + score;
	}
}


Programming question 1

Define a Husband Husband class with name, age, wife attributes

Define a wife Wife class, with name, age, husband attributes

There is a getInfo method in the husband class, which can display his name, age, and his wife's name and age

There is a getInfo method in the wife class, which can display her name, age, and her husband's name and age

Define a test class, create wife and husband objects, and test

/*
 * 
 * 编程题1
定义一个丈夫Husband类,有姓名、年龄、妻子属性
定义一个妻子Wife类,有姓名、年龄、丈夫属性
丈夫类中有一个getInfo方法,其中,能显示自己的姓名,年龄,和他的妻子的姓名,年龄
妻子类中有一个getInfo方法,其中,能显示自己的姓名,年龄,和她的丈夫的姓名,年龄
定义一个测试类,创建妻子和丈夫对象,然后测试
 */
public class Test {
	public static void main(String[] args) {
		Husband husband = new Husband("Tom", 22);
		Wife wife = new Wife("Susan", 20);
		husband.setWife(wife);
		wife.setHusband(husband);
		System.out.println(husband.getInfo());
		System.out.println(wife.getInfo());
	}
}

public class Husband {
	private String name;
	private int age;
	private Wife wife;

	public Husband(String name, int age) {
		this.name = name;
		this.age = age;
	}

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

	public String getName() {
		return name;
	}

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

	public int getAge() {
		return age;
	}

	public void setWife(Wife wife) {
		this.wife = wife;
	}

	public Wife getWife() {
		return wife;
	}

	public String getInfo() {
		return "丈夫叫:" + name + "年龄是:" + age + "妻子叫:" + wife.getName() + "年龄是:" + wife.getAge();
	}
}

public class Wife {
	private String name;
	private int age;
	private Husband husband;

	public Wife(String name, int age) {
		this.name = name;
		this.age = age;
	}

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

	public String getName() {
		return name;
	}

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

	public int getAge() {
		return age;
	}

	public void setHusband(Husband husband) {
		this.husband = husband;
	}

	public Husband getHusband() {
		return husband;
	}

	public String getInfo() {
		return "妻子叫:" + name + "年龄是:" + age + "丈夫叫:" + husband.getName() + "年龄是:" + husband.getAge();
	}
}


Programming question 2

Define the bank account class Account, which has attributes: card number cid, balance balance, and belongs to the user Customer   

The bank account class Account has methods:

(1) getInfo(), return String type, return the detailed information of the card

(2) Withdraw method withdraw(), the parameters are designed by yourself, if the withdrawal is successful, it returns true, and if it fails, it returns false

(3) Save money method save(), the parameters are designed by yourself, if the money is successfully saved, it returns true, and if it fails, it returns false

Among them, the Customer class has attributes such as name, ID number, contact number, and home address. The Customer class has a method say(), which returns a String type and returns his personal information.

Create bank account class objects and user class objects in the test class Bank, and set and display information.

/*
 * 定义银行账户类Account,有属性:卡号cid,余额balance,所属用户Customer   
银行账户类Account有方法:
(1)getInfo(),返回String类型,返回卡的详细信息
(2)取钱方法withdraw(),参数自行设计,如果取钱成功返回true,失败返回false
(3)存钱方法save(),参数自行设计,如果存钱成功返回true,失败返回false
   
其中Customer类有姓名、身份证号、联系电话、家庭地址等属性
    Customer类有方法say(),返回String类型,返回他的个人信息。

在测试类Bank中创建银行账户类对象和用户类对象,并设置信息,与显示信息
 */

public class Bank {
	public static void main(String[] args) {
		Customer c = new Customer("Tom", 1001, 123456789, "地球");
		Account a = new Account(123456, 1000, c);
		System.out.println(c.say());
		System.out.println(a.getInfo());
		System.out.println(a.save(1000));
		System.out.println(a.getInfo());
		System.out.println(a.withdraw(300));
		System.out.println(a.getInfo());
	}
}

public class Account {
	private long cid;
	private int balance;
	private Customer customer;
	
	public long getCid() {
		return cid;
	}

	public void setCid(long cid) {
		this.cid = cid;
	}

	public int getBalance() {
		return balance;
	}

	public void setBalance(int balance) {
		this.balance = balance;
	}

	public Customer getCustomer() {
		return customer;
	}

	public void setCustomer(Customer customer) {
		this.customer = customer;
	}

	public String getInfo(){
		return "卡号是:" + cid + "\n" + "余额是:" + balance;
	}

	public Account(long cid, int balance, Customer customer) {
		super();
		this.cid = cid;
		this.balance = balance;
		this.customer = customer;
	}

	public boolean withdraw(int m){
		if(m>=balance){
			return false;
		}else{
			balance -= m;
			return true;
		}
	}
	
	public boolean save(int m){
		if(m<=0){
			return false;
		}else{
			balance += m;
			return true;
		}
	}
}

public class Customer {
	private String name;
	private long id;
	private long phone;
	private String address;
	
	public Customer(String name, long id, long phone, String address) {
		this.name = name;
		this.id = id;
		this.phone = phone;
		this.address = address;
	}

	public String getName() {
		return name;
	}

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

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public long getPhone() {
		return phone;
	}

	public void setPhone(long phone) {
		this.phone = phone;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String say(){
		return "姓名:" + name +  "\n" + "身份证号:" + id + "\n" + 
				"电话号码:" + phone + "\n" + "地址:" + address;
	}
}


Method usage

哪个选项和show()方法重载
class Demo{
    void show(int a,int b,float c){}
}

A.void show(int a,float c,int b){}//yes

B,void show(int a,int b,float c){}//一模一样。不可以出现在同一个类中。

C.int show(int a,float c,int b){return a;}//yes。

D.int show(int a,float c){return a;}//yes


Method declaration and call

(1) declare a cylinder type,

(2) Declare attributes: the radius of the bottom edge, and the height

(3) Declaration method:

A: The function of the method: print the details of the cylinder in the method

The radius of the base of a cylinder is xxx, the height is xxx, the area of ​​the base is xxx, and the volume is xxx.

B: The function of the method: return the bottom area

C: Function of method: return volume

D: The function of the method: assign the radius and height of the bottom edge of the cylinder

E: Function of the method: Assign values ​​to the radius and height of the bottom edge of the cylinder, and return the result of the assignment

If the radius or height of the bottom edge is <=0, the assignment fails and returns false, otherwise returns true

(4) and test

//声明圆柱体
class Cylinder{
	double radius;//底边半径
	double height;//高
	
	/*
	A:方法的功能:在方法中打印圆柱体的详细信息
	圆柱体的底边的半径是xxx,高是xxx,底面积是xxx,体积是xxx。
	*/
	void printDetails(){
		//double area = Math.PI * radius * radius;//底面积
		//double volume = area * height;//体积
		
		//System.out.println("圆柱体的底边的半径是" + radius +" ,高是" + height + ",底面积是"+ area +",体积是"+volume +"。");
	
		//调用本类的方法
		System.out.println("圆柱体的底边的半径是" + radius +" ,高是" + height + ",底面积是"+ getArea() +",体积是"+getVolume() +"。")
	}
	
	//B:方法的功能:返回底面积 
	double getArea(){
		double area = Math.PI * radius * radius;//底面积
		return area;
	}
	
	//C:方法的功能:返回体积
	double getVolume(){
		
		//double area = Math.PI * radius * radius;//底面积
		//double volume = area * height;//体积
		//return volume;
		
		double volume = getArea() * height;//体积
		return volume;
	}
	
	//D:方法的功能:为圆柱体的底边的半径,和高赋值
	void setValue(double r, double h){
		radius = r;
		height = h;
	}
	
	/*
	E:方法的功能:为圆柱体的底边的半径,和高赋值,并返回赋值的结果
	如果底边的半径或高为<=0,赋值失败,返回false,否则返回true
	*/
	boolean setRadiusAndHeight(double r, double h){
		if(r<=0 || h<=0){
			return false;
		}
		//radius = r;
		//height = h;
		setValue(r,h);
		return true;
	}
	
}

class TestMethodExer{
	public static void main(String[] args){
		//1、创建对象
		Cylinder c = new Cylinder();
		//c.radius = 2.0;
		//c.height = 2;
		c.setValue(2.0,2);
		
		c.printDetails();
		
		System.out.println("底面积: " + c.getArea());
		System.out.println("体积: " + c.getVolume());
		
		boolean flag = c.setRadiusAndHeight(3.0, 5);
		if(!flag){// 如果flag = false, !flag结果就是true,条件成立
			System.out.println("赋值失败");
		}else{
			c.printDetails();
		}
	}
}


method overloading

Method overloading (overload) must satisfy ________

A. Methods defined in different classes B. Methods defined in the same type

C. The method names must be the same D. The return types must be the same

E. The parameters must be different F. The parameters can be the same

Answer: BCE


write the output

class Demo {
    public static void main(String[] args) {
        show(0);
        show(1);
    }

    public static void show(int i) {
        switch(i) {
            default:
            i+=2;
            case 1:
            i+=1;
            case 4:
            i+=8;
            case 2:
            i+=4;
        }
        System.out.println("i="+i);
    }
}

Answer: i=15

           i=14


write the output

class Demo {
    public static void main(String[] args) {
        int x = 1;
        for(show('a'); show('b') && x<3; show('c')) {
            show('d'); 
            x++;
        }
    }

    public static boolean show(char ch) {
        System.out.print(ch);
        return true;
    }
}

Answer: abdcbdcb


What is the result of running the following code?

public class Test1 {
	public static boolean foo(char c) {
		System.out.print(c);
		return true;
	}

	public static void main(String[] args) {
		int i = 0;
		for (foo('A'); foo('B') && (i < 2); foo('C')) {
			i++;// 1 2
			foo('D');
		}
	}
}

Answer: ABDCBDCB


object-oriented

Explanation of the three major characteristics of object-oriented

Answer: Object-oriented has three major characteristics: encapsulation, inheritance, and polymorphism. (If you want to answer four, you can add the feature of abstraction)

1. Inheritance:

Inheritance is a hierarchical model of linking classes, and allows and encourages the reuse of classes, it provides a way to explicitly express commonality. A new class of objects can be derived from an existing class, a process called class inheritance. The new class inherits the characteristics of the original class, the new class is called the derived class (subclass) of the original class, and the original class is called the base class (parent class) of the new class. A derived class can inherit methods and instance variables from its base class, and the class can modify or add new methods to make it more suitable for special needs.

2. Encapsulation:

Encapsulation is to surround the process and data, and the access to the data can only be through the defined interface. Object-oriented computing begins with the fundamental concept that the real world can be represented as a collection of fully autonomous, encapsulated objects that access other objects through a protected interface.

3. Polymorphism:

Polymorphism refers to allowing objects of different classes to respond to the same message. Polymorphism includes parametric polymorphism and containment polymorphism. The polymorphic language has the advantages of flexibility, abstraction, behavior sharing, and code sharing, and it solves the problem of the same name of application functions very well.

4. Abstraction:

To abstract is to ignore those aspects of a subject that are irrelevant to the current goal in order to pay fuller attention to aspects that are relevant to the current goal. Abstraction does not intend to understand all the problems, but only to select a part of them, and not to use some details for the time being. Abstraction includes two aspects, one is process abstraction, and the other is data abstraction.


The difference between the scope public, private, protected, and when it is not written by default

Commonly used access restriction modifiers in java are public, private, protected, and do not write, and the modifiers that are not written are also called default modifiers or friendly modifiers.

1. Member variables and functions modified by private can only be accessed in the class itself and inner classes.

2. Protected modified member variables and functions can be accessed by the class itself, subclasses, and classes in the same package.

3. Publicly modified member variables and functions can be accessed by classes, subclasses, classes in the same package, and any other class.

4. By default (not written), it belongs to a kind of package access, that is, it can be accessed by the class itself and classes in the same package.


find fault

public class Something {
   void doSomething () {
       private String s = "";
       int l = s.length();
   }
}

Is there something wrong?

Answer: False. Local variables cannot be preceded by any access modifiers (private, public, and protected).


Garbage collection of Java's memory management (understand)

Allocation: The corresponding memory space is automatically allocated by the JVM

Release: The garbage collection mechanism provided by the JVM automatically releases the memory space

Garbage collection mechanism (GC: Garbage Collection): Reclaim the heap memory occupied by garbage objects. Java's garbage collection mechanism is a capability provided by the JVM, which is dynamically collected by a separate system-level garbage collection thread in an irregular manner during idle time.

Garbage Object : An object that is no longer pointed to by any references.


Interview questions:

Question: Is it possible to notify the garbage collection mechanism to collect garbage in the program?

Yes, by calling System.gc(); or Runtime.getRuntime().gc();

Ask again: Is garbage collection performed immediately after calling System.gc(); or Runtime.getRuntime().gc();?

No, this call will not immediately start the garbage collection mechanism to start recycling, but it will speed up the operation of the garbage collection mechanism.

public class TestGC {
	public static void main(String[] args)throws Exception {
		for (int i = 0; i < 10; i++) {
			MyClass m = new MyClass();//这里本次循环完,本次创建的对象就成为垃圾了
			System.out.println("创建第" + (i+1) + "的对象:" + m);
		}
		
		//通知垃圾回收机制来收集垃圾
		System.gc();
		
		//为了延缓程序结束
		for (int i = 0; i < 10; i++) {
			Thread.sleep(1);
			System.out.println("程序在继续....");
		}
	}
}
class MyClass {
	//这个方法是垃圾回收机制在回收它的对象时,自动调用,理解成对象留临终遗言的方法
	public void finalize() {
		System.out.println("轻轻的我走了.....");
	}
}


constructor

Whether the constructor Constructor can be overridden

Answer: Constructor cannot be inherited, so Override cannot be overridden, but Overload can be overloaded


Program to create a Box class, define three variables in it to represent the length, width and height of a cube, and define a method to find the volume of the cube. Creates an object that finds the volume of a cube of given dimensions. (provides a parameterless constructor and a parameterized constructor)

public class Box {
	private int length;
	private int width;
	private int height;

	public Box() {
		super();
	}

	public Box(int length, int width, int height) {
		super();
		this.length = length;
		this.width = width;
		this.height = height;
	}

	public int getarea() {
		return length * width * height;
	}
}


define a circle type

Provides a method for displaying the circumference of a circle

Provides a method to display the area of ​​a circle

Provides a parameterless constructor and a parameterized constructor

public class Circle {
	private int r;

	public Circle() {
		super();
	}

	public Circle(int r) {
		super();
		this.r = r;
	}

	public void getCircumferent() {
		System.out.println("圆的周长为:" + 2 * Math.PI * r);
	}

	public void getArea() {
		System.out.println("圆的面积为:" + Math.PI * r * r);
	}
}


Design a Dog class with name, color and age attributes, define a constructor to initialize these attributes, and define an output method show() to display its information.

Provides a parameterless constructor and a parameterized constructor

public class Dog {
	String name;
	String color;
	int age;

	public Dog() {
		super();
	}

	public Dog(String name, String color, int age) {
		super();
		this.name = name;
		this.color = color;
		this.age = age;
	}

	public void show() {
		System.out.println("狗狗的名字为:" + name + "狗狗的颜色为:" + color + "狗狗的年龄为:" + age);
	}
}


write a human class

Attributes: name, gender, age; provide a parameterless constructor and a parameterized constructor

Method: (1) The method of self-introduction (2) The method of eating

Create an object "Zhang San"

public class Person {
	private String name;
	private char gender;
	private int age;

	public Person() {
		super();
	}

	public Person(String name) {
		super();
		this.name = name;
	}

	public void selfIntroduction(String name, char gender, int age) {
		System.out.println("我叫:" + name + ",性别:" + gender + ",年龄:" + age);
	}

	public void eat() {
		System.out.println("人吃饭");
	}

	public static void main(String[] args) {
		Person person = new Person("张三");
		person.selfIntroduction("张三", '男', 20);
	}
}


Write a car class:

Attributes: brand; car length; color; price;

Create five objects: "Jetta", "BMW", "Rolls Royce", "Cruze", "Malibu"

Provides a parameterless constructor and a parameterized constructor

public class Car {
	private String brand;
	private int length;
	private String color;
	private int price;

	public Car() {
		super();
	}

	public Car(String brand) {
		super();
		this.brand = brand;
	}

	public static void main(String[] args) {
		Car car1 = new Car("捷达");
		Car car2 = new Car("宝马");
		Car car3 = new Car("劳斯莱斯");
		Car car4 = new Car("科鲁兹");
		Car car5 = new Car("迈锐宝");
	}
}


The result of running the following program is:

public class Test1 {

	public static void main(String[] args) {
		new A(new B());
	}
}

class A {
	public A() {
		System.out.println("A");
	}

	public A(B b) {
		this();
		System.out.println("AB");
	}
}

class B {
	public B() {
		System.out.println("B");
	}
}

Answer:

B

A

AB


About parameter passing

exercise one

write the result

public class Test {
	public static void leftshift(int i, int j) {
		i += j;
	}

	public static void main(String args[]) {
		int i = 4, j = 2;
		leftshift(i, j);
		System.out.println(i);
	}
}

Answer: 4 

It has nothing to do with the leftShift function.


exercise two

write the result

public class Demo {
	public static void main(String[] args) {
		int[] a = new int[1];
		modify(a);
		System.out.println(a[0]); //
	}

	public static void modify(int[] a) {
		a[0]++;
	}
}

Answer: 1


Exercise three

public class TestA {
	int i;

	void change(int i) {
		i++;
		System.out.println(i);
	}

	void change1(TestA t) {
		t.i++;
		System.out.println(t.i);
	}

	public static void main(String[] args) {
		TestA ta = new TestA();
		System.out.println(ta.i); //0
		ta.change(ta.i);//1
		System.out.println(ta.i); //0
		ta.change1(ta); //1
		System.out.println(ta.i);//1
	}
}


Exercise four

class Value {
	int i = 15;
}

class Test {
	public static void main(String argv[]) {
		Test t = new Test();
		t.first();
	}

	public void first() {
		int i = 5;
		Value v = new Value();
		v.i = 25;
		second(v, i);
		System.out.println(v.i);
	}

	public void second(Value v, int i) {
		i = 0;
		v.i = 20;
		Value val = new Value();
		v = val;
		System.out.print(v.i + " " + i);
	}
}

A.15 0 20

B.15 0 15

C.20 0 20

D.0 15 20

·Answer: A


Exercise five

What is the result of executing the following code

public static void main(String[] args) {
	int i = 0;
	change(i);
	i = i++;
	System.out.println("i = " + i);
}
public static void change(int i){
	i++;
}

Answer: i = 0


public static void main(String[] args) {
	String str = new String("world");
	char[] ch = new char[]{'h','e','l','l','o'};
	change(str,ch);
	System.out.println(str);
	System.out.println(String.valueOf(ch));
}
public static void change(String str, char[] arr){
	str = "change";
	arr[0] = 'a';
	arr[1] = 'b';
	arr[2] = 'c';
	arr[3] = 'd';
	arr[4] = 'e';
}

Answer:

world

abcde


public class Test {
	int a;
	int b;

	public void f() {
		a = 0;
		b = 0;
		int[] c = { 0 };
		g(b, c);
		System.out.println(a + " " + b + " " + c[0]);
	}

	public void g(int b, int[] c) {
		a = 1;
		b = 1;
		c[0] = 1;
	}

	public static void main(String[] args) {
		Test t = new Test();
		t.f();
	}
}

Answer: 1 0 1


short answer

When an object is passed as a parameter to a method, the method can change the properties of the object and return the changed result, so is it value passing or reference passing?

Answer: It is passed by value. The Java programming language has only pass-by-value parameters. When an object instance is passed as a parameter to a method, the value of the parameter is a reference to the object. The content of the object can be changed in the called method, but the reference of the object will never change


epilogue


I will continue to update the article! I hope everyone will click three times , your encouragement is the motivation for the author to keep updating

Guess you like

Origin blog.csdn.net/qq_34025246/article/details/126913962