-1

like this

package com.levent.consultantapi.service;

import java.util.List;

import com.levent.consultantapi.model.Consultant;

public interface ConsultantService {
    
    List<Consultant> getConsultants();
    Consultant createConsultant(Consultant consultant);
    Consultant getConsultantById(Long id);
    Consultant updateConsultantById(Long id, Consultant consultant);
    Consultant deleteConsultantById(Long id);

}


package com.levent.consultantapi.service.consultant.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.levent.consultantapi.model.Consultant;
import com.levent.consultantapi.repository.ConsultantRepository;
import com.levent.consultantapi.service.ConsultantService;

@Service
public class ConsultantServiceImpl implements ConsultantService {
    
    @Autowired
    private ConsultantRepository consultantRepository;
    
    @Override
    public List<Consultant> getConsultants() {
        return consultantRepository.list();
    }

    @Override
    public Consultant createConsultant(Consultant consultant) {
        return consultantRepository.create(consultant);
    }

    @Override
    public Consultant getConsultantById(Long id) {
        return consultantRepository.get(id);
    }

    @Override
    public Consultant updateConsultantById(Long id, Consultant consultant) {
        return consultantRepository.update(id, consultant);
    }

    @Override
    public Consultant deleteConsultantById(Long id) {
        return consultantRepository.delete(id);
    }

}

What's the advantage of doing this and we can do it without interface only class of service?
what's about doing all code in controller?

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////

1 Answers1

1

In java Abstraction can be a achieved with the help of interface and abstract class. So the main reason to use interface is to achieve abstraction.

Now let's suppose you are writing an api( may be payment gateway api Or etc) which will be use by some other company Or developer outside of your company. So now you can not show / share them your implementation class( actual code) . You will share your interface method and they will make use of it. That's it.

Take an another example of T. V remote, the people who development the T. V. Remote just provided us some buttons like volume up, down, next etc. It is not our Headache that how these button works.

Hope this answer will be helpful.

Sourabh Chopade
  • 498
  • 5
  • 13