Preguntas de práctica del capítulo orientadas a objetos (parte 1) y preguntas de la entrevista

Instanciación de clase

Código

Escriba una clase de estudiante, incluyendo nombre, género, edad, id, atributos de puntuación, que son String, String, int, int y double.
Un método say se declara en la clase, que devuelve el tipo String, y la información de retorno del método contiene todos los valores de los atributos.
En el método principal de otra clase StudentTest, cree un objeto Student, acceda al método say y a todos los atributos e imprima el resultado de la llamada.

responder:

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

Problema de programación 1

Defina una clase de esposo con nombre, edad y atributos de esposa;

Definir una clase de esposa, con nombre, edad y atributos del esposo;

Hay un método getInfo en la clase de marido, que puede mostrar su nombre, edad y el nombre y la edad de su esposa;

Hay un método getInfo en la clase esposa, que puede mostrar su nombre, edad y el nombre y la edad de su esposo;

Defina una clase de prueba, cree objetos de esposa y esposo y luego pruebe.

 

responder:

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

resultado de la operación:

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

Pregunta de programación 2

Defina la clase de cuenta bancaria Cuenta, que tiene atributos: número de tarjeta cid, saldo saldo y pertenece al usuario Cliente   

La cuenta bancaria tiene métodos:

(1) getInfo (), tipo de cadena de retorno, detalles de la tarjeta de retorno

(2) Método Withdraw (), los parámetros los diseña usted mismo, si el retiro es exitoso, devolverá verdadero, y si falla, devolverá falso

(3) El método save () para ahorrar dinero, los parámetros los diseña usted mismo, si el ahorro es exitoso, devuelve verdadero, y si falla, devuelve falso

   

La categoría de Cliente tiene atributos como nombre, número de identificación, número de contacto y dirección particular.

    La clase Customer tiene un método say (), que devuelve un tipo String y devuelve su información personal.

Cree un objeto de clase de cuenta bancaria y un objeto de clase de usuario en el banco de prueba, establezca la información y muestre la información

 

Análisis: similar a la idea y la redacción de la pregunta anterior, puede omitirla aquí.

Uso del método

Qué opción y método show () está sobrecargado

clase Demo {

    void show (int a, int b, float c) {}

}

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

B, void show (int a, int b, float c) {} // Exactamente lo mismo. No puede aparecer en la misma clase.

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

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

Respuesta: ACD

 

Declaración de método y llamada

(1) Declare un tipo de cilindro,

(2) Declarar atributos: el radio y la altura del borde inferior

(3) Método de declaración:

A: La función del método: imprime la información detallada del cilindro en el método

El radio del lado inferior del cilindro es xxx, la altura es xxx, el área inferior es xxx y el volumen es xxx.

B: La función del método: devolver el área inferior

C: Función del método: volumen de retorno

D: La función del método: asignar un valor al radio del lado inferior del cilindro y la altura

E: La función del método: asignar un valor al radio y la altura del fondo del cilindro y devolver el resultado de la asignación.

Si el radio o la altura del borde inferior es <= 0, la asignación falla y devuelve falso; de lo contrario, devuelve verdadero

(4) y prueba

responder:

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

resultado de la operación:

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

Sobrecarga de métodos

La sobrecarga del método (sobrecarga) debe satisfacer ________

A. Métodos definidos en diferentes clases B. Métodos definidos en el mismo tipo

C. El nombre del método debe ser el mismo D. El tipo de retorno debe ser el mismo

E. Los parámetros deben ser diferentes F. Los parámetros pueden ser los mismos

 

Respuesta: AEC

Escribir salida

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

responder:

i=15
i=14

Escribir salida

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

Escribir salida 

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

Orientado a objetos

Descripción de las tres características de la orientación a objetos

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

Alcance público, privado, protegido y la diferencia cuando no está escrito por defecto

Encontrar mal

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

Recolección de basura de la gestión de memoria de Java (entender)

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

Preguntas de entrevista:

Pregunta: ¿Se puede notificar al mecanismo de recolección de basura que recolecte basura en el programa?

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

Preguntar de nuevo: después de llamar a System.gc (); o Runtime.getRuntime (). Gc ();, ¿se realiza la recolección de basura inmediatamente?

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

¿Se puede anular el constructor?

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

Cree una clase Box mediante programación, defina tres variables en ella para representar el largo, ancho y alto de un cubo, y defina un método para encontrar el volumen del cubo. Crea un objeto y encuentra el volumen de un cubo de un tamaño determinado.

(Proporcione un constructor sin parámetros y un constructor parametrizado)

pass

Definir un tipo de círculo

Proporcionar un método para mostrar la circunferencia de la circunferencia.

Proporcionar un método para mostrar el área de un círculo.

Proporcionar un constructor sin parámetros y un constructor parametrizado

pass

Diseñe una clase Dog con atributos de nombre, color y edad, defina el constructor para inicializar estos atributos y defina el método de salida show () para mostrar su información.

Proporcionar un constructor sin parámetros y un constructor parametrizado

pass

Definir una clase para describir puntos de coordenadas

(1) Tiene la función de calcular la distancia desde el punto actual al origen

(2) Encuentre la distancia a cualquier punto (m, n)

(3) Encuentre la distancia a cualquier punto (Punto p)

(4) Con función de visualización de puntos de coordenadas, formato de visualización (x, y)

(5) Proporcione un constructor sin parámetros y un constructor con parámetros

responder:

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

resultado de la operación:

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

Escribe una clase humana

Atributos: nombre, género, edad; proporcione un constructor sin parámetros y un constructor con parámetros

Métodos: (1) Método de autointroducción (2) Método de alimentación

Crea un objeto "Zhang San"

pass

Escriba una clase de automóvil:

Atributos: marca; capitán; color; precio;

Crea cinco objetos: "Jetta", "BMW", "Rolls-Royce", "Cruz", "Meribao"

Proporcionar un constructor sin parámetros y un constructor parametrizado

pass

Escribe una clase de curso:

Atributos: nombre del curso, horas de clase, profesor de clase;

Crea cinco objetos: "lenguaje c", "programación java", "programación de red php", "c ++", "estructura de datos"

Proporcionar un constructor sin parámetros y un constructor parametrizado

pass

El resultado del siguiente programa es:

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

Acerca del paso de parámetros

Ejercicio uno

Escribe el resultado.

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  形参

Ejercicio dos

Escribe el resultado.

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 实参

Ejercicio tres

Escribe el resultado.

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

Ejercicio cuatro

Escribe el resultado

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不变

Ejercicio cinco

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

Ejercicio seis

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(//形参?){
		
	}
}

responder:

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]

¿Cuál es el resultado de la ejecución del siguiente código?

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。

Los resultados del siguiente programa:

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

responder:

world
abcde

¿Cuál es el resultado del siguiente código?

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

Respuesta corta

Cuando un objeto se pasa como parámetro a un método, el método puede cambiar las propiedades del objeto y devolver el resultado modificado. Entonces, ¿se pasa por valor o por referencia?

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

Complemente el código en la función comparar y no agregue otras funciones.

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的半径比较大");
	}
}

responder:

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的半径比较大");
    }
}

 

Supongo que te gusta

Origin blog.csdn.net/qq_41048982/article/details/109347234
Recomendado
Clasificación