简体   繁体   中英

How is this interface and class being implemented?

I am fairly new in this field.

Here is a code snippet:

JAXBContext jobj = JAXBContext.newInstance(Employee.class);

Marshaller mobj = jobj.createMarshaller();   

Employee emp1=new Employee(1,"Jordan",50000);  
  
mobj.marshal(emp1, new FileOutputStream("employee.xml")); 

Now I know JAXBContext is an abstract class and Marshaller is an interface.

Now how can createMarshaller()(Return type Marshaller) return a Marshaller object? Is JAXBContext implementing Marshaller? Even if implementing then how it is returning the object? Cuz I have tried to implement an Interface in a class and then created a method that returns the object of that Interface but it was throwing error.

Tried to simulate:

Interface: public interface

 Marshall {
    
    public Marshall marshaller();
    
    public int m();

}

Class:

public class JaxB implements Marshall{
    
    
    @Override
    public Marshall marshaller() {
        
        return new Marshall(); //error
        
    }

    public int m(){
        return 1;
    }

}

Can you please correct my Class?

Simply create a method inside that class and add the return statement with the parameters you want to send and then create an object in the Class you want to call the method which will receive the output of the method

Here is how to have a method return an instance of an interface:

interface Foo {}

class FooImplementation implements Foo {}

class FooFactory {
    Foo getFoo() {
        return new FooImplementation();
    } 
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM