Skip to main content

Java OOP 面向对象

1. What is the differences between Overriding and Overloading?

Method Overloading 重载

  • Both have same method name. 方法名相同
  • Both have different arguments. 参数列表不同

Method Overriding 重写

  • It must have same method name as that of parent class method. 方法名相同
  • It must have same arguments as that of parent class method. 参数列表相同
  • It must have either the same return type or covariant return type (child classes are covariant types to their parents). 返回类型相同
  • It must not throw broader checked exceptions. 不能抛出更广泛的异常
  • It must not have a more restrictive access modifier (if parent method is public, then child method cannot be private/protected). 不能有更严格的访问修饰符

Method overloading by changing data type of arguments

class Calculate {
void sum (int a, int b) {
System.out.println("sum is" + (a + b)) ;
}
void sum (float a, float b) {
System.out.println("sum is" + (a + b));
}
Public static void main (String[] args) {
Calculate cal = new Calculate();
cal.sum (8, 5); //sum(int a, int b) is method is called.
cal.sum (4.6f, 3.8f); //sum(float a, float b) is called.
}
}
Sum is 13
Sum is 8.4

Method overloading by changing number of argument

class Demo {
void multiply(int l, int b) {
System.out.println("Result is" + (l * b)) ;
}
void multiply(int l, int b, int h) {
System.out.println("Result is" + (l * b * h));
}
public static void main(String[] args) {
Demo ar = new Demo();
ar.multiply(8, 5); //multiply(int l, int b) is method is called
ar.multiply(4, 6, 2); //multiply(int l, int b,int h) is called
}
}
Result is 40
Result is 48

Example of Method Overriding

class Animal {
public void eat() {
System.out.println("Eat all eatables");
}
}

class Dog extends Animal {
//eat() method overridden by Dog class.
public void eat() {
System.out.println("Dog like to eat meat");
}

public static void main(String[] args) {
Dog d = new Dog();
d.eat();
}
}
Dog like to eat meat

2. What is the differences between super and this?

  • We can use super() as well this() only once inside constructor.
  • Both this() and super() refer to objects, so neither can be used in a static context.
  • this Keyword
    • this is a reference variable that refers to the current object. 当前对象的引用变量
    • Call to this() must be the first statement in constructor. 必须放在构造方法的开头
  • super Keyword
    • super() is used to call Base class’s constructor(i.e, Parent’s class). 用于调用父类的构造方法
    • super() is added in each class constructor automatically by compiler if there is no super() or this().
class Playground {
public static void main(String[ ] args) {
Child c = new Child();
}
}

class Parent {
Parent() {
System.out.println("Parent");
}
}

class Child extends Parent {
Child() {
super();
System.out.println("Child");
}

}
Parent
Child

3. What is the Java load sequence?

static variable -> static block -> constructor

4. What is Polymorphism? And how Java implements it?

In programming, polymorphism refers to the same object exhibiting different forms and behaviors. In Java, we have two ways to implement it,

  • Method Overloading (compile time)

    • If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.
    • There are two ways to overload the method in java : by changing number of arguments, by changing the data type.
  • Method Overriding (run time)

    • Method overriding is the process of redefining a parent class’s method in a subclass.
    • Method must have same name and parameters as in the parent class for overriding.
    • For any method, a child class can use the implementation in the parent class or make its own implementation.

5. What is Encapsulation? How Java implements it? And why we need encapsulation?

  • Encapsulation in OOP refers to binding the data and the methods to manipulate that data together in a single unit (class).
  • To make all data members of the class private, and use setter/getter methods to access data.

6. What is Interface and what is abstract class? What are the differences between them?

abstract class is a "is or not" relationship, while Interface is a "has or not" relationship.

Abstract classInterface
Abstract class can have abstract and non-abstract methods.Interface can have only abstract methods. Since Java8, it can have default & static methods also.
Abstract class doesn't support multiple inheritance.Interface supports multiple inheritance.
Abstract class can have final, non-final, static and non-static variables.Interface has only static and final variables.
Abstract class can provide the implementation of interface.Interface can't provide the implementation of abstract class.
The abstract keyword is used to declare abstract class.The interface keyword is used to declare interface.

For eg. dog has eat() and sleep() methods.

// by abstract class
public abstract class Dog {
public abstract void eat();
public abstract void sleep();
}

// by interface
public interface Dog {
public abstract void eat();
public abstract void sleep();
}

Now we want to add a new feature on dog, CatchBall()

// define an interface with a CatchBall method
public interface CatchBall() {
public abstract void catchBall();
}

// use abstract class to define a Dog class
public abstract class Dog {
public abstract void eat();
public abstract void sleep();
}

class SpecialDog extends Dog implements CatchBall {
public void eat() {
//....
}
public void sleep() {
//....
}
public void catchBall() () {
//....
}
}

7. What are the SOLID Principles?

  • Single responsibility principle: A class should have one and only one reason to change, meaning that a class should have only one job.
// 只负责 calculate area
public class AreaCalculator {
private float result;

public float getResult() {
return this.result;
}

public float calculateArea(Triangle t) {
this.result = h * b / 2;
}
}

// 只负责 print
public class Printer {
public printInJson(float number) {
jsonPrinter.initialize();
jsonPrinter.print(this.result);
jsonPrinter.close();
}
}
  • Open close principle: Objects or entities should be open for extension but closed for modification.
public interface Shape {
public float getArea();
}

public class Triangle implements Shape {
public float getArea() {
return b * h / 2;
}
}

// 不需要改变,只需要取定义新的形状
public class AreaCalculator {

private float result;

public float getResult() {
return this.result;
}

public float calculateArea(Shape s) {
this.result = s.getArea();
}
}
  • Liskov substitution principle: Every subclass or derived class should be substitutable for their base or parent class.
  • Interface segregation principle: A client should never be forced to implement an interface that it doesn’t use.
public class 2DShape {
abstract public float calculateArea();
}

public class 3DShape {
abstract public float calculateVolumn();
}

public class Rectangle extends 2DShape {
// Good design
}

public class Cube extends 3DShape {
// Good design
}
  • Dependency inversion principle: Classes should depend on abstract class or interfaces instead of concrete classes.
// interface是抽象的class
// 有class想实现接口的时候, 需要实现接口内所有的函数
public interface Shape {
public float getArea();
}

public class Triangle implements Shape {
public float getArea() {
return b * h / 2;
}
}

public class AreaCalculator {

private float result;

public float getResult() {
return this.result;
}

public float calculateArea(Shape s) {
this.result = s.getArea();
}
}

7. What do you understand by the Open-Closed Principle (OCP)?

Open close principle: Objects or entities should be open for extension but closed for modification.

public interface Shape {
public float getArea();
}

public class Triangle implements Shape {
public float getArea() {
return b * h / 2;
}
}

// 不需要改变,只需要取定义新的形状
public class AreaCalculator {

private float result;

public float getResult() {
return this.result;
}

public float calculateArea(Shape s) {
this.result = s.getArea();
}
}

8. Liskov’s substitution principle states that if class B is a subtype of class A, then object of type A may be substituted with any object of type B. What does this actually mean? (from OA ) choose your answer.

  • It mean that if the object of type A can do something, the object of type B could also be able tp perform the same thing
  • It means that all the objects of type A could execute all the methods present in its subtype B
  • It means if a method is present in class A, it should also be present in class B so that the object of type B could substitute object of type A.
  • It means that for the class B to inherit class A, objects of type B and objects of type A must be same.