Object Oriented (Part 1) Chapter Practice Questions and Interview Questions

Class instantiation

Code

Write a Student class, including name, gender, age, id, score attributes, which are String, String, int, int, and double.
A say method is declared in the class, which returns String type, and the return information of the method 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.

answer:

class Student {
    private String name;
    private String gender;
    private int age;
    private int id;
    private double score;

    public Student(String name, String gender, int age, int id, double score) {
        this.name = name;
        this.gender = gender;
        this.age = age;
        this.id = id;
        this.score = score;
    }
    public String say(){
        return "名字:" + name + "; 性别:"+ gender + "; 年龄"+ age + "; id:" + id + ";成绩:"+score;
    }
}
public class StudentTest {
    public static void main(String[] args) {
        Student s=new Student("素媛","女",22,520,100);
        System.out.println(s.say());
    }
}

Programming Problem 1

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

Define a Wife class, with name, age, and 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 your name, age, and her husband's name and age;

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

 

answer:

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

    public Husband(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public void getinfo(){
        System.out.println("我是丈夫:"+name +" 年龄:"+age+" 妻子:"+wife.name+" 年龄:"+wife.age);
    }
}

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

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

    public void getinfo(){
        System.out.println("我是妻子:"+name +" 年龄:"+age+" 丈夫:"+husband.name+" 年龄:"+husband.age);
    }
}

public class TestOfLove {
    public static void main(String[] args) {
        Husband hb=new Husband("健哥",18);
        Wife wf=new Wife("媛姐",19);
        hb.wife=wf;
        wf.husband=hb;
        hb.getinfo();
        wf.getinfo();
    }
}

operation result:

我是丈夫:健哥 年龄:18 妻子:媛姐 年龄:19
我是妻子:媛姐 年龄:19 丈夫:健哥 年龄:18

Programming Question 2

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

Bank account account has methods:

(1) getInfo(), return String type, return card details

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

(3) The save() method of saving money, the parameters are designed by yourself, if the saving is successful, it returns true, and if it fails, it returns false

   

The Customer category 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 a bank account class object and a user class object in the test bank, and set the information, and display the information

 

Analysis: Similar to the idea and writing of the previous question, you can skip it here.

Method use

Which option and show() method is overloaded

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){}//Exactly the same. Cannot appear in the same class.

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

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

Answer: ACD

 

Method declaration and call

(1) Declare a cylinder type,

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

(3) Method of declaration:

A: The function of the method: print the detailed information of the cylinder in the method

The radius of the bottom side of the cylinder is xxx, the height is xxx, the bottom area is xxx, and the volume is xxx.

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

C: Function of the method: return volume

D: The function of the method: assign a value to the radius of the bottom side of the cylinder and the height

E: The function of the method: Assign a value to the radius and height of the bottom 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 it returns true

(4) and test

answer:

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();
        }
    }
}

operation result:

圆柱体的底边的半径是2.0 ,高是2.0,底面积是12.566370614359172,体积是25.132741228718345。
底面积: 12.566370614359172
体积: 25.132741228718345
圆柱体的底边的半径是3.0 ,高是5.0,底面积是28.274333882308138,体积是141.3716694115407。

Method overload

Method overload (overload) must satisfy ________

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

C. The method name must be the same D. The return type must be the same

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

 

Answer: BCE

Write 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 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;
}
}
abdcbdcb

Write output 

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');
        }
    }
}
ABDCBDCB

Object-oriented

Description of the three characteristics of object-oriented

答:面向对象有三大特点:封装、继承、多态。(如果要回答四个,可加上 抽象性 这一特点)
1.继承性:
继承是一种联结类的层次模型,并且允许和鼓励类的重用,它提供了一种明确表述共性的方法。对象的一个新类可以从现有的类中派生,这个过程称为类继承。新类继承了原始类的特性,新类称为原始类的派生类(子类),而原始类称为新类的基类(父类)。派生类可以从它的基类那里继承方法和实例变量,并且类可以修改或增加新的方法使之更适合特殊的需要。
2.封装性:
封装是把过程和数据包围起来,对数据的访问只能通过已定义的界面。面向对象计算始于这个基本概念,即现实世界可以被描绘成一系列完全自治、封装的对象,这些对象通过一个受保护的接口访问其他对象。
3. 多态性:
多态性是指允许不同类的对象对同一消息作出响应。多态性包括参数化多态性和包含多态性。多态性语言具有灵活、抽象、行为共享、代码共享的优势,很好的解决了应用程序函数同名问题。
4.抽象性:
抽象就是忽略一个主题中与当前目标无关的那些方面,以便更充分地注意与当前目标有关的方面。抽象并不打算了解全部问题,而只是选择其中的一部分,暂时不用部分细节。抽象包括两个方面,一是过程抽象,二是数据抽象。

Scope public, private, protected, and the difference when not written by default

Find wrong

public class Something {
   void doSomething () {
       private String s = "";
       int l = s.length();
   }
}
有错吗?
答案: 错。局部变量前不能放置任何访问修饰符 (private,public,和protected)。

Garbage collection of Java memory management (understand)

分配:由JVM自动为其分配相应的内存空间
释放:由JVM提供垃圾回收机制自动的释放内存空间
垃圾回收机制(GC:Garbage Collection):将垃圾对象所占用的堆内存进行回收。Java的垃圾回收机制是JVM提供的能力,由单独的系统级垃圾回收线程在空闲时间以不定时的方式动态回收。
垃圾对象:不再被任何引用指向的对象。

Interview questions:

Question: Can the garbage collection mechanism be notified to collect garbage in the program?

能,通过调用System.gc();或Runtime.getRuntime().gc();

Ask again: After calling System.gc(); or Runtime.getRuntime().gc();, is garbage collection performed immediately?

不是,该调用并不会立刻启动垃圾回收机制开始回收,但会加快垃圾回收机制的运行。
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

Can Constructor be overridden?

答:构造器Constructor不能被继承,因此不能重写Override,但可以被重载Overload

Create a Box class programmatically, 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. Create an object and find the volume of a cube of a given size.

(Provide a parameterless constructor and a parameterized constructor)

pass

Define a circle type

Provide a method to display the circumference of the circumference

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

Provide a parameterless constructor and a parameterized constructor

pass

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

Provide a parameterless constructor and a parameterized constructor

pass

Define a class to describe coordinate points

(1) It has the function of calculating the distance from the current point to the origin

(2) Find the distance to any point (m, n)

(3) Find the distance to any point (Point p)

(4) With coordinate point display function, display format (x, y)

(5) Provide a constructor without parameters and a constructor with parameters

answer:

public class Point {
    public int X;
    public int Y;

    public Point() {
    }
    public Point(int x, int y) {
        X = x;
        Y = y;
    }
    public double  OXY(){
        return Math.sqrt(X*X+Y*Y);
    }
    public double AnyXY(int x,int y){
        return Math.sqrt((X-x)*(X-x)+(Y-y)*(Y-y));
    }
    public double PXY(Point P){
        return Math.sqrt((P.X-X)*(P.X-X)+(P.Y-Y)*(P.Y-Y));
    }

    public static void main(String[] args) {
        Point P=new Point(1,1);
        Point P1=new Point(3,3);
        System.out.println("P与原点的距离:"+P.OXY());
        System.out.println("P到(2,2)的距离"+P.AnyXY(2,2));
        System.out.println("P到P1的距离"+P.PXY(P1));
    }
}

operation result:

P与原点的距离:1.4142135623730951
P到(2,2)的距离1.4142135623730951
P到P1的距离2.8284271247461903

Write a human class

Attributes: name, gender, age; provide a constructor with no parameters and a constructor with parameters

Methods: (1) Method of self-introduction (2) Method of eating

Create an object "Zhang San"

pass

Write a car class:

Attributes: brand; captain; color; price;

Create five objects: "Jetta", "BMW", "Rolls-Royce", "Cruz", "Meribao"

Provide a parameterless constructor and a parameterized constructor

pass

Write a course class:

Attributes: course name; class hours; class teacher;

Create five objects: "c language", "java programming", "php network programming", "c++", "data structure"

Provide a parameterless constructor and a parameterized constructor

pass

The result of 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");
    }
}
答案:
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);
    }
}
答案:4  形参

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]++;
} 
} 
答案: 1 实参

Exercise three

Write the result.

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); //
ta.change(ta.i);//
System.out.println(ta.i); //
ta.change1(ta);  //
System.out.println(ta.i);//
}
}
答案:
0
1
0
1
1

Exercise four

Write the result

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
答案:A

v = val;//局部形参v的引用指向原来传入的v,改为指向val,原来传入的v不变

Exercise five

1. public class Test {
2. int x= 12;
3. public void method(int x) {
4. x+=x;
5. System.out.println(x);
6. }
7. }
Given:
34. Test t = new Test();
35. t.method(5);
What is the output from line 5 of the Test class?
A. 5
B. 10
C. 12
D. 17
E. 24
答案: B

优先使用局部变量的X

Exercise Six

import java.util.Arrays;

public class PassValueExer2{
	public static void main(String[] args){
		int[] array = {3,2,5,1,7};
		
		//调用sort方法,实现从大到小排序
		//在此处补充代码
		....
		
		//显示结果
		System.out.println("排序后的结果是:" + Arrays.toString(array));
	}
	
	//要求使用冒泡排序完成
	public void sort(//形参?){
		
	}
}

answer:

import java.util.Arrays;

public class PassValueExer2{
    public static void main(String[] args){
        int[] array = {3,2,5,1,7};

        //调用sort方法,实现从大到小排序
        //在此处补充代码
        PassValueExer2.sort(array);

        //显示结果
        System.out.println("排序后的结果是:" + Arrays.toString(array));
    }

    //要求使用冒泡排序完成
    public static  void sort(int[] a){
        int pos=0;
        int i=a.length-1;
        while(i>0){
            for (int j=0;j<i;j++){
                if (a[j]<a[j+1]){
                    int t=a[j];
                    a[j]=a[j+1];
                    a[j+1]=t;
                    pos=j;
                }
            }
            i=pos;
        }
    }
}
排序后的结果是:[7, 5, 3, 2, 1]

What is the execution result of the following code

public class PassValueExer2{
    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++;
    }
}
答案:0

典型的i=i++的问题 ,可上网查阅资料,我理解的是右边的i先赋值给左边的i,然后右边的i再自加存到隐身临时变量里,自加后的值并没有作用于左边的i,所以左边的i为右边初始的i。

The results of the following program:

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

What is the result of the following code?

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){//a1 b0 c1
        a = 1;
        b = 1;
        c[0] = 1;
    }
    public static void main(String[] args) {
        Test t = new Test();
        t.f();
    }
}
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 passed by value or by reference?

答:是值传递。Java 编程语言只有值传递参数。当一个对象实例作为一个参数被传递到方法中时,参数的值就是对该对象的引用。对象的内容可以在被调用的方法中改变,但对象的引用是永远不会改变的

Complement the code in the compare function and do not add other functions.

class Circle {
	private double radius;

	public Circle(double r) {
		radius = r;
	}

	public Circle compare(Circle cir) {
		// 程序代码
		/*
		 * if(this.radius>cir.radius) return this; return cir;
		 */

		// return (this.radius>cir.radius)?this: cir;

	}
}

class TC {
	public static void main(String[] args) {
		Circle cir1 = new Circle(1.0);
		Circle cir2 = new Circle(2.0);
		Circle cir;
		cir = cir1.compare(cir2);
		if (cir1 == cir)
			System.out.println("圆1的半径比较大");
		else
			System.out.println("圆2的半径比较大");
	}
}

answer:

class Circle {
    private double radius;

    public Circle(double r) {
        radius = r;
    }

    public Circle compare(Circle cir) {
        // 程序代码
        /*
         * if(this.radius>cir.radius) return this; return cir;
         */

        // return (this.radius>cir.radius)?this: cir;
        return  this.radius >cir.radius ? this : cir;
    }
}

public  class TC {
    public static void main(String[] args) {
        Circle cir1 = new Circle(1.0);
        Circle cir2 = new Circle(2.0);
        Circle cir;
        cir = cir1.compare(cir2);
        if (cir1 == cir)
            System.out.println("圆1的半径比较大");
        else
            System.out.println("圆2的半径比较大");
    }
}

 

Guess you like

Origin blog.csdn.net/qq_41048982/article/details/109347234