java interfaces

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Anvesh Tummala
    New Member
    • Jan 2014
    • 5

    java interfaces

    Code:
    public interface Pet {
    public abstract void beFriendly();
    public abstract void play();
    }
    
    public class Dog extends Canine implements Pet {
    public void beFriendly() {...}
    public void play() {..}
    public void roam() {...}
    public void eat() {...}
    }
    If Canine too have a beFriendly and play methods, what method of beFriendly will be executed.
    Last edited by Rabbit; Jan 3 '14, 04:14 PM. Reason: Please use [CODE] and [/CODE] tags when posting code or formatted data.
  • Nepomuk
    Recognized Expert Specialist
    • Aug 2007
    • 3111

    #2
    If Canine has a beFriendly and play method then you have no problem; Dog needs an implementation of both functions (as it implements Pet) and due to it extending Canine it has an implementation of each. If you implement it as you suggest above it won't make any difference though, as Dog implements both functions and so the implementations in Dog will be used.
    But here, look at this example:
    Code:
    public class Canine {
    	public void beFriendly() {
    		System.out.println("I'm friendly");
    	}
    	
    	public void play() {
    		System.out.println("I'm playing");
    	}
    }
    Code:
    public class Dog extends Canine implements Pet {
    	
    	public static void main(String[] args) {
    		Dog dog = new Dog();
    		dog.beFriendly();
    		dog.play();
    		dog.roam();
    		dog.eat();
    	}
    
    	public void roam() {
    		System.out.println("I'm roaming");
    	}
    
    	public void eat() {
    		System.out.println("I'm eating");
    	}
    }
    This will print the text:
    Code:
    I'm friendly
    I'm playing
    I'm roaming
    I'm eating
    Also, functions defined in interfaces are automatically abstract, so you don't have to put the abstract modifier into an interface.

    Comment

    • Anvesh Tummala
      New Member
      • Jan 2014
      • 5

      #3
      If we add the following code in public class Dog extends Canine implements Pet what will be the result
      Code:
        public void beFriendly() {
              System.out.println("I'm friendly dog");
          }
       
          public void play() {
              System.out.println("I'm a dog and I am playing");
          }
      Last edited by Rabbit; Jan 3 '14, 08:22 PM. Reason: Please use [CODE] and [/CODE] tags when posting code or formatted data. Second warning.

      Comment

      • Nepomuk
        Recognized Expert Specialist
        • Aug 2007
        • 3111

        #4
        Have you tried this?

        Comment

        Working...