简体   繁体   中英

Is inheritance possible without Encapsulation in java?

Is inheritance possible without Encapsulation in java? Is this possible?

Yes, it is possible. Inheritance and Encapsulation do not depend on each other, but when used both, they provide more flexible and powerful application structures.

For instance, below, there is inheritance without encapsulation. Note - that it is a bad approach, and do not use this approach in your projects. It is just for the demonstration purposes.

class A {
   public int a;
   public int b;
   public String c;

   public A() {

   }

   protected void someMethod() {

   }
}

class B extends A {
  // a, b, c from the parent A class are accessible here

  public int d;
  public String e;

  public B() {
    super();
  }

  // someMethod() is accessible here
}

In the code above, there is no encapsulation implemented, all class fields are public, and can be changed from outside.

But this approach prevents you from changing the structure of your classes withour affecting the rest of your code.

And it is strongly recommended to combined use of inheritance and encapsulation in your applications.

Hide your class structure and implementations over this structure. And show (make public) only methods to operate with the class instance internals from the outside.

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