Inheritance in Java

I have a little confusion regarding inheritance in Java... or perhaps the general concept... I was trying to write polymorphic code and I encountered this question...
When a class inherits from another class, all the member variable is supposed to be inherited right? So, if I have something like:
abstract class super{
private SomeObject someObj;
public abstract void foo();
class sub extends super{
public void foo(){
someObj = new SomeObject();
the class sub does not know about someObj. I tried different visibility for someObj but none worked...
Something I have not tried, but might as well settle my question with inheritance here, is that if the super class were a concrete class, are all member variables inherited into its subclasses regardless of the member variables' visibility?
Can someone clear my confusion? Thanx!

I changed the visibility to protected and then public and it still would not compile... I think there might be something to do with the abstract.
However, I remember that long time ago (I had this question for a while) I tested the concept with concrete classes and it seems that the private member variable is not inherited...
That confused me quite a bit because I thought that when a parent class's member variable was private, a sub-class's object has no access to that variable of an instance of the parent class. But the subclass should have inherited it and should have its own copy of that variable. And when the visibility was protected, that's when an object of the subclass has access to that variable of an object of the parent class...
I think the confusion comes from if visibility is meant for the class or for the instances of the class...

Similar Messages

  • Constructors and Inheritance in Java

    Hi there,
    I'm going over access modifiers in Java from this website and noticed that the following output is displayed if you run the snippet of code.
    Cookie Class
    import javax.swing.*;
    public class Cookie {
         public Cookie() {
              System.out.println("Cookie constructor");
         protected void foo() {
              System.out.println("foo");
    }ChocolateChip class
    public class ChocolateChip extends Cookie {
         public ChocolateChip() {
              System.out.println("ChocolateChip constructor");
         public static void main(String[] args) {
              ChocolateChip x = new ChocolateChip();
              x.foo();
    }Output:
    Cookie constructor
    ChocolateChip constructor
    fooI've been told that constructors are never inherited in Java, so why is "Cookie constructor" still in the output? I know that ChocolateChip extends Cookie, but the Cookie constructor isn't enacted when the new ChocolateChip object is defined... or is it?
    If you can shed any light on this, I would greatly appreciate it.
    Many thanks!

    896602 wrote:
    I've been told that constructors are never inherited in JavaThat is correct. If they were inherited, that would mean that, just by virtue of Cookie having a c'tor with some particular signature, ChocoChip would also "automatically" have a c'tor with that same signature. However, that is not the case.
    , so why is "Cookie constructor" still in the outputBecause invoking a constructor always invokes the parent class's c'tor before any of our own c'tor's body executes, unless the first statement is this(...), to invoke some other c'tor of ours. If this is the case, eventually down the line, some c'tor of ours will not have an explicit this(...) call. It will either have an explicit super(...) call, or no call at all, which ends up leading to the compiler generating a call to super().
    Note that the ability to call super(...) does not mean that that c'tor was inherited.
    I know that ChocolateChip extends Cookie, but the Cookie constructor isn't enacted when the new ChocolateChip object is defined... or is it?Yes, it is. As I pointed out above, if we don't explicitly call this(...) or super(...), then a call to super() is inserted by the compiler.

  • Simulating Multiple Inheritance in Java

    Problem:
    I am trying to obfuscate code and create wrapper classes to access code implementation. Problem is that some parameters in methods have different types. (i.e.
    public class Example{
    ExampleImpl exampleImpl;
    public void setExample(Problem exam) {
    exampleImpl.setExample(exam); //complile error
    //error message: problemImpl is not of type problem
    public class ExampleImpl {
    public void setExample(ProblemImpl exam) {
    //do something
    The objects Problem and ProblemImpl are abstract class that provode some implementation.
    I know I have to sumulate multipule inheritance but its really have to changed the abstract classes to inherate each other. Problem with that is the ProblemImpl abstract class will be obfuscated.
    Any suggestions.

    Not quite following you but perhaps
    java.lang.reflect.proxy
    could be of service

  • Ambiguous inheritance in Java?

    Hello, everyone,
    I have heard through preventing from inheriting from multiple classes, Java is free of ambiguous inheritance (so called diamond inheritance). For example, class B derives from class A, class C derives from class A and class D derives from both class B and C, if class B and class C both overwrite the same method of class A, when invoking this method from class D, it will be ambiguous (method from class B or class C?).
    I thought Java is free of this, but I have written a sample which has such ambiguous.
    public interface Foo1 {
         void Fun();
    public interface Foo2 {
         void Fun();
    public class FooImpl implements Foo1, Foo2 {
         public void Fun() {
              // TODO Auto-generated method stub
    }In class FooImpl, it has a method Fun which its super interface Foo1 and Foo2 both have. And suppose some clients will use FooImpl by Foo1 or Foo2 (other than using FooImpl itself), and they have to use the unified implementation of class FooImp, other than specifc implementation of Fun for Foo1 and Fun for Foo2. Is that ambiguous?
    And suppose some clients will use FooImpl and they will invoke Foo function of class FooImpl, but they do not know whether it is Foo for Foo1 or Foo for Foo2. Even though Fun in interface Foo1 and Foo2 have no concrete implementation, the same function in different interface is possible to have different meanings, isn't it? How will they know which one they are using? Is that also ambiguous?
    Thanks in advance,
    George

    as per the JLS
    "It is possible for an interface to inherit more than
    one method with the same signature (�8.4.2). Such a
    situation does not in itself cause a compile-time
    error. The interface is considered to inherit all the
    methods. However, a compile-time error occurs if, for
    any two such inherited methods, either they have
    different return types or one has a return type and
    the other is void. (The throws clauses do not cause
    errors in this case.)"The problem isn't compilation errors, but semantic errors. Just because two methods share the same name doesn't mean they do the same thing. One framework could have an interface with a method called "eatsShootsAndLeaves" that tells a client supplied object to eat, shoot and leave. Another could have the same method to test if a client object eats shoots and leaves. Both might return a boolean. The compiler would be happy. There would be no way to implement one method that satisfied the requirements of both frameworks.

  • Multiple inheritance in Java

    Why it is sometimes said that interfaces provide a form of multiple inheritance?
    Do you agree that interfaces can provide multiple inheritance? Explain.
    Some people say that Java does not support multiple inheritance, and others: a class can implement more than 1 interface. Isn't that multiple inheritance?
    Thanks

    >
    Some people say that Java does not support multiple
    inheritance, and others: a class can implement more
    than 1 interface. Isn't that multiple inheritance?Sort of, but you don't inherit any implementation from an interface.

  • No multiple inheritance in Java. Interfaces used.

    Hi,
    In java a class can extend only one class while the interface can extend any number of interfaces.
    Class extending only one class avoids multiple inheritance.
    Can you explain me the reason of avoiding this in classes and allowing interfaces to extend any number of interfaces ?

    Hi,
    In java a class can extend only one class while the
    interface can extend any number of interfaces.
    Class extending only one class avoids multiple
    inheritance.
    Can you explain me the reason of avoiding this in
    classes and allowing interfaces to extend any number
    of interfaces ?The real question is: do you have a need for multiple inheritance?
    If so, I would be glad to hear about this concrete problem.

  • Abt "import" statement & Inheritance in Java

    Hi, All
    As we (Java Programmers) know we'll be using "import java.Math.*" or similar for importing custom/Java packages.
    If i have suppose imported "import java.math.BigDecimal;" in a Class 'A' & and iam extending this class 'A' in another class 'B', if i want to use any method from 'BigDecimal' here in this class(i.e., in class 'B') again i need to import "import java.Math.BigDecimal; " .
    so, my question is :
    1) When we import in one class a package and same package in another class does java import it twice (or) what it does?
    2) when I extend a class , why don't this import facility don't get extended.(I think u got my point.)
    PS: If any problems in this mail technical or what so ever, iam sorry.
    Thanks in advance.

    Importation is just a compiler trick. It has nothing to do with runtime.
    The separation of sources files brings the necessity of repeated imports from file to file.
    You can verify this if you create one source file and put several classes in it: you won't have to import
    more than once.
    so, my answers are :
    1) Each time the compiler encounters an import package.Class statement, it checks the CLASSPATH for the class existence and loads the class definition.
    When a reference to the class is done anywhere in the following statements, the compiler checks the referenced entity (member, method...) against the class definition.
    2) If the extending class is contained in the same source file, then only one import will be needed.
    Hope this helped,
    Regards.

  • Mulitiple Inheritance in java

    Please help me in implementing this condition using java
    we have a parent
    abstract class Person.
    we have two classes
    Class Teacher extends Person
    and
    Class Student extends Person
    this structure cannot be modified as of now.
    Now i need to write a class "TeacherStudent" which has both Teacher and Student Properties.
    i have a method in Teacher class to compute salary that takes a instance of Teacher as parameter and another method to compute grade in Student that takes an instance of Student as parameter. i must be able to pass the new class written to both this methods.
    HOW TO ACHEIVE THIS IN JAVA? CAN ANYONE HELP

    I am really sorry for misguiding you and everybody else. You are right! Interfaces cannot extend classes. On the otherhand they can extend interfaces.
    I remember seeing some programs where they used the 'extends' keyword as in "interfaceA extends interfaceB" and I was mistaken that the extends word is only used with classes. Hence I was pretty sure that interfaces can extend classes.
    However upon writing some sample code, the compiler slapped me black and blue for doing such a thing :)
    Thanks for helping me discover this fact!

  • Class members don't override via inheritance in Java?

    Consider following code:
    class A
    protected int v=1;
    void print()
    System.out.println(v);
    class B extends A
    protected int v=2;
    public class m
    public static void main(String args[])
    B kl=new B();
    kl.print();
    What do you think, what should be the program's output?
    It is "1" - I think in C++ it would be "2" (I am not sure of this). Why the member variable "v" doesn't override the one from parent class in "print" method? Do you think it is ok?
    Consider changing B class definition to this:
    class B extends A
    protected int v=2;
    B() { v=3; }
    The output is still "1",
    but:
    class B extends A
    // protected int v=2;
    B() { v=3; }
    And the output is "3".
    So we have two different variables: A.v and B.v.
    Shouldn't be only one there, depending on the class of the object?

    Considder the following code.
    public class a
       int a;
       public a()
          a = 1;
       public int a()
          return a;
       public int a(a a)
          a.a = a.a++;
          if(this.a == a.a)
             return a();
          else
             return a.a;
    }Are you surprised that it actually compiles? Do you have any doubt about the behavour? Do you think it is smart to reuse the symbol a? Do you think it is smart to reuse the symbol v? Because that is what you do. You have two different integers, both with the name v. Then it gets confusing. My advice: Give them different names!

  • SWIG - C++/Java and multiple interface inheritance - SWIG typemaps

    In C++ I have the following. Can someone explain how to use SWIG typemaps to accomplish multiple interface inheritance in Java? I understand there is a javainterfaces typemap built into SWIG however I am such a newb with SWIG I really don't know where to start.
    class IRemoteSyncIO
    public:
      virtual ~IRemoteSyncIO () {}
    protected:
      IRemoteSyncIO () {}
    private:
      IRemoteSyncIO (const IRemoteSyncIO&);
      IRemoteSyncIO& operator= (const IRemoteSyncIO&);
    class IRemoteAsyncIO
    public:
      virtual ~IRemoteAsyncIO () {}
    protected:
      IRemoteAsyncIO () {}
    private:
      IRemoteAsyncIO (const IRemoteAsyncIO&);
      IRemoteAsyncIO& operator= (const IRemoteAsyncIO&);
    class RemoteMpe : public IRemoteSyncIO, public IRemoteAsyncIO
    }Thanks!

    Actually now I understand what you mean.... Ok, now I am going to modify the problem slightly and add Interface2 into the picture. The new code is:
    interface Interface1<SelfType extends Interface1<SelfType>>
    interface Interface2
    class Superclass implements Interface1<Superclass>
    class Dependant<Type extends Interface1<Type>>
       public static <Type extends Interface1<Type> & Interface2> Dependant<Type> getInstance(Class<Type> c)
         return new Dependant<Type>();
    class Subclass extends Superclass implements Interface2
      public Subclass()
        Dependant<Subclass> dependant = Dependant.getInstance(Subclass.class);
    }Now, previously I could replace:
    Dependant<Subclass> dependant = Dependant.getInstance(Subclass.class);
    with
    Dependant<Superclass> dependant = Dependant.getInstance(Superclass.class);
    and it solved the problem, but now that Type must implement Interface2 I cannot.
    The reason I added this requirement is that this is actually what is going on in my applicationI had made mistakely omited this detail from the original use-case.
    Can you think up of a possible solution to this new use-case?
    Thanks,
    Gili

  • A little question about inheritance

    Can someone explain this to me?
    I have been reading about inheritance in Java. As I understand it when you extend a class, every method gets "copied" to the subclass. If this is so, how come this doesn't work?
    class inherit {
        int number;
        public inherit(){
            number = 0;
        public inherit(int n){
            number = n;
    class inherit2 extends inherit{
        public inherit2(int n, int p){
            number = n*p;
    class example{
        public static void main(String args[]){
            inherit2 obj = new inherit2();
    }What I try to do here is to extend the class inherit with inherit2. Now the obj Object is of inherit2 class and as such, it should inherit the constructor without parameters in the inherit class or shouldn't it ??? If not, then should I rewrite all the constructors which are the same and then add the new ones??

    I believe you were asking why SubClass doesn't have the "default" constructor... after all, shouldn't SubClass just have all the contents of SuperClass copy-pasted into it? Not exacly. ;)
    (code below... if you'd like, you can skip the first bit, start at the code, and work your way down... depending on if you just started, the next bit may confuse rather than help)
    Constructors are special... interfaces don't specify them, and subclasses don't inherit them. There are many cases where you may not want your subclass to display a constructor from it's superclass. I know this sounds like I'm saying "there are many cases where you won't want a subclass to act exactly like a superclass, and then some (extend their functionality)", but its not, because constructors aren't how an object acts, they're how an object gets created.
    As mlk said, the compiler will automatically create a default constructor, but not if there is already a constructor defined. So, unfortunatley for you, there wont be a default constructor made for SubClass that you could use to create it.
    class SuperClass { //formerly inherit
    int number;
    public SuperClass () { //default constructor
    number = 0;
    public SuperClass (int n) {
    number = n;
    class SubClass extends SuperClass { //formerly inherit2
    //DEFAULT CONSTRUCTOR, public SubClass() WILL NOT BE ADDED BY COMPILER
    public SubClass (int n, int p) {
    number = n*p;
    class Example {
    public static void main(String [] args) {
    //attempted use of default constructor
    //on a default constructorless subclass!
    SubClass testSubClass = new SubClass();
    If you're still at a loss, just remember: "Constructors aren't copy-pasted down from the superclass into the subclass!" and "Default constructors aren't added in if you add your own constructor in" :)
    To get it to work, you'd have to add the constructor you used in main to SubClass (like doopsterus did with inheritedClass), or use the constructor you defined in SubClass for when you make a new one in main:
    inherit2 obj = new inherit2(3,4);
    Hope that cleared things up further, if needed. By the way, you should consider naming your classes as a NounStartingWithACapital, and only methods as a verbStartingWithALowercase

  • ADF Business Component Type MAP Oracls vs Java

    what the advantages and disadvantages from each one map type
    thank in advance

    Take a look at this link in developer's guide:
    http://docs.oracle.com/cd/E16162_01/web.1112/e16182/bcintro.htm#sm0062
    The Java Extended for Oracle type map and the Oracle Domains type map handle numeric data differently. When you create a new application the default type map Java Extended for Oracle maps numeric data to the java.math.BigDecimal >class, which inherits from java.math.Number. The java.math.BigDecimal default matches the way the Fusion web application view layer, consisting of ADF Faces components, preserves alignment of numeric data (such as numeric values >displayed by ADF Faces input fields in a web page). Whereas the Oracle Domains type map, which maps numeric data to the oracle.jbo.domain.Number class, may not display the data with the alignment expected by certain ADF Faces >components. Aside from this alignment issue, the Oracle Domains type map remains a valid choice and applications without ADF Faces components will function without issue.Thanks,
    Navaneeth

  • Java Interview questions!!!!!!!!!!!!

    Hi folks,
    I had an interview with a small company a few days ago.
    Below is a list of the questions that they asked me.
    Some of these are not familiar to me at all.
    Does anyone have the answer for these?
    (1) Draw UML diagrams that express the following concepts:
    (a) Class C and class B are subclasses of class A.
    (b) Class P has two private fields int x and int y and one
    public method setXY(int x1, int y1)
    (c) bob is and object of class Bob.
    (d) Class A objects contain one or more objects of class B.
    (e) Interface A is implemented by class B and class C.
    (2) Define the following computer science terms:
    (a) Primitive type
    (b) type conversion
    (c) narrowing / widening a type.
    (d) reference type
    (e) type casting
    (3) (a) Give an example of variable shadowing.
    (b) (2pts) Explain the difference between method hiding and
    overriding methods.
    (c) Give an example of marker interface.
    (d) Suppose class A implements two interfaces C and D. Each of these
    has a method public void getRichQuick() but C's method
    throws CaughtBySECException and D's method throws
    AntitrustException. What will the compiler do?
    (4) (a) With respect to subclassing what does restriction mean?
    (b) How do we implement restriction in Java?
    (c) Suppose we have two interfaces in Java: I2 which extends
    I1. Is I2[] a subtype of Object[] ? Why or why
    not?
    (d) What is multiple inheritance?
    (e) Give a way to achieve the effect of multiple inheritance in Java.
    (5) (a) In a Java class definition what is an initialization. Give an
    example.
    (b) Give the order in which the following three things would be
    initialized when a subclass B of class A is created:
    (i) an explicit initializer in B, (ii) an explicit initializer
    in A, and (iii) an initalization statement in a constructor of A.
    (6) (a) On what methods and classes should one use /** ... */ comments?
    (b) For javadoc to detect these comments where relative to these
    methods/classes should the comment occur?
    (c) Explain how to use each of the following javadoc tags:
    (i) @since (ii) @see (iii) @param
    (7) Define the following terms with respect to their object-orientation
    meaning. Give an example of (b) and (c).
    (a) framework
    (b) idiom
    (c) design pattern
    (8) Give each of the things needed for the canonical form for public classes
    in Java.
    (9) Class A and Class B each contain identical blocks of code 30 lines long.
    Class A extends Class C and Class B extends Class D. Suggest a way to
    avoid the code duplication using factorization. What kind of
    factorization did you use?
    (10) Give the UML diagrams for the folowing design patterns:
    (a) Strategy
    (b) Iterator
    (c) Factory
    (d) Template
    (e) Singleton

    I think I can help you with a few points:
    2
    a. Primitive types are byte, short, char, int, long, float, double and boolean. They tell the compiler the type of the variable and thus how much memory needs to be set aside to store the variable in memory.
    b. Converting from one type to another which kinda links in with c. Widenening is the process of changing, for example and byte to an int (no explicit cast is needed) because a byte (8 bits) can fit into an int (32 bits).
    However the reverse is not true (obviously) so an explivit cast is needed to tell the compiler that you meant to do it (as information can be lost).
    e.g. int i = 3000;
    byte b = (byte)i;
    obviously a byte can only hold values up to 127 so converting this int to a byte changes the value. You have to look at the bits and understand a bit of binary code for this.
    This kinda answers part e. too.
    d. A reference type is a pointer to a cariable or object (I think thats what its getting at). eg int i = 32; i is a reference to the memory address where the computer stored the value 32.
    4d.e Multiple inheritance is when a subclass inherits from more than one base class. In java this is not possible (java only supports single inheritance with the extends keyword). However, java overcomes this with interfaces as a class, although it can only extends one base class, can implement as many interfaces as it likes in a comma seperated list.
    I hope this helps you on your way. The fact of the matter is, the majority of your questions can be found in any decent book on java (and UML). Also look at the java tutorial online.
    For example 1a is simply a box with two other boxes beneath with arrows pointing upwards to the base class (not downwards as would seem reasonable).
    The best way to learn all this stuff is to read it then try it yourself! That way you'll remember it much better.
    Good luck

  • SQL Dates and JAVA

    Hi All,
    Firstly I am a complete newbie with java code so apologies in advance!! To cut a long story short I have inherited a java app which is of great importance to the company I am working for - in fact its of such importance that the creator saw no reason to document any of its usage - apparently it ran for several years before falling over by which time its author had long gone! - at that point it had to be ported over to new hardware.
    Basically the app consists of javascript running from within Tomcat - the data is then dumped into a mysql database.
    I have managed to get it working again...except for the date -
    the user enters the date in the form eg 04/07/2007 and this is then (or should be ) entered into the database in the format yyyy-MM-dd
    Now , when I start mysql up with logging I can see that the insert statement is completing except for the date (which is left as 0000-00-00). It is attempting to enter the date in the following format.
    #2006-07-04#
    it seems to be the '#' thats screwing it up. If i enter the insert statement manually without the '#' everything is fine. So question is why is this happening and how do I change it.
    The last pice of code before the insert is attempted is
    stmta.executeUpdate(qry.toString())
    I suppose that the toString gives a string representation of the date - I have got myself a java CBT which I am working through :) but I hoped one of you guys would be able to point me in the right direction in the meantime
    Many Thanks

    yes - I have been through it I think the relevant code is this
    rdate = request.getParameter("rdate")
    String ndateissued = request.getParameter("ndateissued");
    if (ndateissued == null) {
    ndateissued = "";
    myformat = new SimpleDateFormat("dd/MM/yyyy");
    Date issueddate = null
    String rdate1 = rdate.substring(8,10) + "/" + rdate.substring(5,7) + "/" + rdate.substring(0,4);
    //String rdate1 = rdate.substring(5,7) + "/" + rdate.substring(8,10) + "/" + rdate.substring(0,4);
    Date rdate2 = myformat.parse(rdate1);
    try {
    if (ndateissued.length() > 0) {
    issueddate = myformat.parse(ndateissued);
    if (issueddate.getTime() < rdate2.getTime()) {
    %> <CENTER><FORM><TABLE>
    <tr><td>Date issued < Date Recei
    ved?????</td></tr>
    </TABLE></FORM></CENTER>
    <%
    return;
    return;
    if (((issueddate.getTime() - rdate2.getTime()) / 3600000) > 2400 ) {
    %> <CENTER><FORM><TABLE>
    <tr><td>Date issued > Date Received + 100 days ?????</td></tr>
    </TABLE></FORM></CENTER>
    <%
    return;
    dstring = myformat.format(issueddate);
    if (!dstring.equals(ndateissued)) {
    %> <CENTER><FORM><TABLE>
    <tr><td>Date issued - out of range</td></tr>
    </TABLE></FORM></CENTER>
    <%
    return;
    ndateissued = ndateissued.substring(6,10) + "-" + ndateissued.substring(3,5) + "-" + ndateissued.substring(0,2);
    } catch (Exception e) {
    %> <CENTER><FORM><TABLE>
    <tr><td>Date issued- parsing error</td></tr>
    </TABLE></FORM></CENTER>
    <%
    return;
    Calendar cal = Calendar.getInstance();
    cal.setTime(rdate2);
    String xdow = cal.get(Calendar.DAY_OF_WEEK) + "";
    directtly after this is the code referencing the insert statement.
    Many Thanks

  • What is the BEST practice - use BO or Java Object in process as webservice

    Hi All,
    I have my BP published as web service. I have defined My process input & output as BOs. My BP talks to DB through DAO layer(written in JAVA) which has Java objects. So I have BO as well as java Objects. Since I am collecting user input in BO, I have to assign individual values contained in BO to Java object's fields.
    I want to reduce this extra headache & want to use either of BO or Java object.I want to know What is the best practice - use BO or Java object as process input. If it is BO,how I can reuse BOs in Java?
    Thanks in advance.
    Thanks,
    Sujata P. Galinde

    Hi Mark,
    Thanks for your response. I also wanted to use java object only. When I use java object as process input argument..it is fine. But when I try to create Process web service, I am getting compilation error - "data type not supported".....
    To get rid of this error, I tried to use heir (BO inheriting from java class). But while invoking process as web service, it is not asking for fields that are inherited from java class.
    Then I created Business Object with a field of type java class... This also is not working. While sending request, it is giving an error that - field type for fields from java class not found.
    Conclusion - not able to use java object as process(exposed as web service) input argument .
    What is the Best & feasible way to accomplist the task - Process using DAO in Java & exposed as web service.
    Thanks & Regards,
    Sujata

Maybe you are looking for