Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java example featuring encapsulation, polymorphism, and inheritance?

I need to produce a project featuring the listed characteristics of object oriented programming using Java.

Could someone look over my quick sample program to confirm that I understand how these characteristics are implemented and that they are all present and done correctly?

package Example;

public class Parent {

    private int a;
    public void setVal(int x){
        a = x;
    }
    public void getVal(){
        System.out.println("value is "+a);
    }
}

public class Child extends Parent{

    //private fields indicate encapsulation
    private int b;
    //Child inherits int a and getVal/setVal methods from Parent
    public void setVal2(int y){
        b = y;
    }
    public void getVal2(){
        System.out.println("value 2 is "+b);
    }
    //having a method with the same name doing different things
    //for different parameter types indicates overloading,
    //which is an example of polymorphism
    public void setVal2(String s){
        System.out.println("setVal should take an integer.");
    }
}
like image 384
user2048643 Avatar asked Feb 06 '13 21:02

user2048643


1 Answers

Your polymorphism example is merely method overloading and that's not actually what the Object Oriented folks mean by polymorphism. They mean how you can have a interface that exposes a method, and the various classes that implement that interface can implement the method to have different behaviors.

See this. Last paragraph of the introduction in particular.

Also, I would suggest that the best way to demonstrate knowledge of polymorhpism in code would necessarily include some client code that uses the polymorphic objects to demonstrate that they can have different, i.e. poly, behaviors.

like image 76
chad Avatar answered Oct 28 '22 02:10

chad