These simple and stupid mistakes that I made during an interview Part 1

文章介绍了Java8中的FunctionalInterface,强调其单抽象方法的特性,以及如何使用它们进行lambda表达式和方法引用,简化代码。同时,讨论了DefaultMethods和StaticMethods的引入,如何在不破坏继承关系的情况下扩展接口功能。示例展示了如何在接口中声明和使用这两种方法。

Introduction

All right, I failed another interview as usual. I always made very simple errors, like yesterday, I had an interv iew with an india company. Their interview questions are more focused on basic knowledge of candidate. I record servral questions which I failed to answer. Here I reviewed them and write the answers out.

1. Functional Interface

The first question is about one the feature of Java 8, functional interface. To be honest, I just have a very ambiguous overview about it.
I write down the answer below.

1.1 Introduction

Functional interface is defined by only have single abstract method, so it is also called SAM interface, but it accepts multiple default and static methods.**

@FunctionalInterface
public interface MyInterface {
    public int add(int a, int b);
}
//Usage
public class App {
    public static void main(String[] args) throws Exception {
        MyInterface myInterface=(x,y)->x+y;
    }
}

You might notice that there is no abstract keyword used before add() method, that is because, by default, a method declared inside a functional interface is abstract.

1.2 Declaration

You might have noticed that the first line of above snippet is @FunctionalInterface annotation. Yes, it’s built-in Java annotation. You must have it to build your own functional interface.
Apart from that, Java also offers some predefined functional interfaces, like Runnable, Callable, Function, Consumer etc.

1.3 Benefits

The main reason why we need functional interfaces is that we can use them in lambda expressions and method references. This way, we reduce boilerplate code.

Before, we would have to use an Anonymous class, like below. But functional interfaces make the code more straightforward to read. For example, an anonymous class is created like this:

public class AnonymousClassExample {
    public static void main(String[] args) {
        Thread thread = new Thread(){
            public void run(){
                System.out.println("Understanding what is an anonymous class");
            }
        };
        thread.start();
    }
}

Now, with Runnable interface, it looks like this.

public class AnonymousClassExample {

    public static void main(String[] args) {

        Runnable runnable = () -> {
            System.out.println("Understanding functional interfaces");
        };
        runnable.run();
    }
}

It’s shorter and easier to read, right?

2. Default method

Another mistake I made is mixed Static method with another feature of Java 8, Default method.
Before Java 8, interface can only contain abstract method. Since Java 8, Static method and Default method are introduced in interface. It hugely expands the functions of interface without breaking the heritance relationship of its derived class.

There’s an interface

public interface MyInterface {
    public int add(int a, int b);
}

User asks to add another mothod into MyInterface, like divid(int, int). With Static method and default method, I can accomplish it without defining a divid(int, int) abstract method.

  • The example of Static method
@FunctionalInterface
public interface MyInterface {
    public int add(int a, int b);
    static double divid(int a, int b){
        System.out.println("I am static");
    }
}
//Usage
public class App {
    public static void main(String[] args) throws Exception {
        System.out.println(MyInterface.divid(3, 3));
    }
}
//result
PS D:\code\FuntionalInterface>  d:; cd 'd:\code\FuntionalInterface'; & 'C:\Program Files\Java\jdk-17.0.2\bin\java.exe' '-XX:+ShowCodeDetailsInExceptionMessages' '-cp' 'D:\code\FuntionalInterface\bin' 'App'
1
  • The example of Default method
@FunctionalInterface
public interface MyInterface {
    public String des="abc";
    public int add(int a, int b);
    default public int divid(int a, int b){
        return a*b;
    }
}
//Usage
public class App {
    public static void main(String[] args) throws Exception {
    	MyInterface myInterface=(x,y)->x+y;
        System.out.println(myInterface.add(1, 1));
    }
}
//result
PS D:\code\FuntionalInterface>  d:; cd 'd:\code\FuntionalInterface'; & 'C:\Program Files\Java\jdk-17.0.2\bin\java.exe' '-XX:+ShowCodeDetailsInExceptionMessages' '-cp' 'D:\code\FuntionalInterface\bin' 'App'
2
  • Difference

Default methods:
A default method is a method declared with the default keyword in a functional interface.
Default methods have a default implementation, which can be overridden by implementations of the functional interface in concrete classes.
Default methods are used to provide a default behavior for the functional interface, but can be customized by concrete classes if needed.
Static methods:
A static method is a method declared with the static keyword in a functional interface.
Static methods are not associated with a particular instance of the functional interface and are called using the name of the functional interface, not an instance of the interface.
Static methods are used to provide utility methods that are associated with the functional interface as a whole, rather than with individual instances of the interface.

“50 Shades of Go: Traps, Gotchas, and Common Mistakes for New Golang Devs” 是一篇针对新的 Go 语言开发者的文章,聚焦于 Go 语言中常见的陷阱、易犯错误和常见误区。它能帮助新手开发者提前了解可能遇到的问题,避免在开发过程中陷入不必要的困境,从而提升开发效率和代码质量。 虽然没有直接的引用内容详细描述其具体内容,但可以推测文章会涵盖以下几类问题: - **语法使用错误**:如变量声明、作用域、类型转换、指针操作等方面容易出错的地方。例如在 Go 语言里,变量声明后必须使用,否则会编译报错;指针的使用不当可能导致空指针异常等。 - **并发编程陷阱**:Go 语言以其强大的并发编程能力著称,但并发编程也是容易出错的重灾区。像竞态条件(race condition)、死锁(deadlock)、资源竞争等问题都可能在多 goroutine 编程中出现。 - **内存管理问题**:Go 语言有自动垃圾回收机制,但开发者仍可能因为对内存分配和回收的理解不足,导致内存泄漏等问题。例如,长生命周期的对象持有短生命周期对象的引用,可能会阻止短生命周期对象被及时回收。 - **切片和映射的使用误区**:切片和映射是 Go 语言中常用的数据结构,但它们有一些特殊的行为。比如切片在扩容时可能会导致性能问题,映射在并发环境下使用需要加锁等。 下面是一个简单的 Go 语言中可能出现的并发编程竞态条件示例: ```go package main import ( "fmt" "sync" ) var counter int var wg sync.WaitGroup func increment() { defer wg.Done() for i := 0; i < 1000; i++ { counter++ // 这里会出现竞态条件 } } func main() { wg.Add(2) go increment() go increment() wg.Wait() fmt.Println("Counter:", counter) } ``` 在上述代码中,两个 goroutine 同时对 `counter` 变量进行自增操作,会出现竞态条件,导致最终结果可能不是预期的 2000。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值