Field inheritance on Java - java

Are fields only inherited "one level up"?
By that I mean that if I have a Superclass to a Class, which then has a Subclass, and the Superclass has a field, the Class will inherit it and the Subclass won't. Is this correct?
And if it is, is there a way to make the Subclass automatically inherit the field from the Superclass given that, as I understand it, there's no way to inherit from two classes at once?
Thank you to anyone who takes the time to answer. I realize my question may be impractical and in reality you'd probably just override the field or something, but I'm not trying to do anything specific, just trying to learn how Java works. Thank you.
Here's my code:
public class SuperClass {
protected int entero;
protected void method(){
entero=1;
}
public class SubClass extends Class {
public SubClass(){}
}
public class Class extends SuperClass {
public Class(){}
}
public static void main(String[] args){
Class object= new Class();
SubClass subobject= new SubClass();
/*This is where I get an error, why?*/
subobject.entero=2;
/*This one is fine*/
object.entero=2;
object.method();
System.out.println(object.entero);
}

Any class B than extends a class A, will inherit A's fields. If a class C extends B, C will inherit all non-private instance fields and methods from A and B, ie transitivity holds.
If a field is private, then one cannot directly change it from a subclass; however, you can get around this by using setter/getter methods.
If a field is protected, then a subclass has direct access to it.
EDIT 1:
In a comment you say that the field is protected, but you still can't access it from a subclass. The only thing I can think of is that you have a situation like this:
class A
{
protected int x;
}
class B extends A
{
private int x;
}
class C extends B
{
private int z = x;
}
This would NOT work because by declaring x again in B, you are hiding the x field from A. So, now C sees x as B's private variable x, which you do not have access to.
EDIT 2:
I'm not going to remove the above edit, because it's informative, but now that you posted your code, it's because your SubClass does not actually extend anything (this was later fixed in an edit).

Inheritance in Java is transitive.
If your classes are Superclass < Class < Subclass, then Subclass inherits all the non-private instance fields and methods provided by Superclass not overridden or hidden by Class or Subclass.
One level of inheritance is specified by the Java Language Specification, section 8.4.8: Inheritance, Overriding and Hiding:
A class C inherits from its direct superclass and direct superinterfaces all abstract
and non-abstract methods of the superclass and superinterfaces that are public,
protected, or declared with default access in the same package as C, and are neither
overridden (§8.4.8.1) nor hidden (§8.4.8.2) by a declaration in the class.

If you have classes that are:
public class SuperClass {
public void methodName() {}
//SuperClass's stuff
}
public class MidClass extends SuperClass {
//MidClass's stuff
}
public class SubClass extends MidClass {
//SubClass's Stuff
}
Then it is perfectly valid to have in your main method:
SubClass sc = new SubClass();
sc.methodName();

Related

How to force a subclass to use a superclass variable?

I am using java and I would like to force all of my subclasses to use the variables of the superclass.
The superclass is abstract and the subclasses implement all of its methods but not the variables.
Is there any way I can force the subclasses to use also the variables of the superclass?
thanks
You cannot "force" the subclass to use your variables. But maybe you are looking for the Template Pattern. This way, you can define a template method in the abstract superclass which defines the structure and the general working of your class. It calls the hook methods which are abstract and have to be provided by implementing classes. You can make it final to prevent subclasses from overriding the template method. Then the subclasses have to implement the abstract hook methods provided, but cannot override the template method.
The keyword super is most of the times used in conjunction to accessing superclass methods, most of the times a constructor from the parent class .
However, you can also use super to access fields of the superclass.
Here is an example of the usage for accessing fields.
public class Base {
public int a = 1;
protected int b = 2;
private int c = 3;
public Base(){
}
}
public class Extended extends Base{
public int a = 4;
protected int b = 5;
private int c = 6;
public Extended(){
}
public void print(){
//Fields from the superclass
System.out.println(super.a);
System.out.println(super.b);
System.out.println(super.c); // not possible
}
}
public static void main(String[] args) {
Extended ext = new Extended();
ext.print();
}
You can always rename the fields in your subclasses not to conflict, but if you want to distinguish a method parameter or local variable from the superclass field, use super as you would use this
Simple. All you need is to let the subclass inherit the superclass through inheritance. this would allow your subclass implement functions of your superclass.
For a more detailed reference kindly visit this link: http://docstore.mik.ua/orelly/java-ent/jnut/ch03_04.htm
Just make the field protected, meaning that it should be visible to all derived classes and can use them in subclasses. If that is what you are tying to imply by saying force.
Like someone said here you can use the template design pattern which will ensure that steps of an algorithm is given in a method so this way you can have the variable used in a method that can be used in a sub class.
The other approach would be to set the access modifier as "protected" which ensures that the subclasses that inherits from the super class can use the variables in the super class

Java Multilevel Inheritance - Protected Instance Variable in Level 1 Class

I have an question which comes under multilevel inheritance in Java. All Three Classes are in Same package
I have class A :
public class A {
protected int x;
}
public class B extends A {
public void doSomething {
// x is visible.agreed, as it is a direct subclass of A
}
}
public class C extends B {
public void doSomething {
// x is still visible, how come? I mean it is at the 2nd level
// I am confused why?
}
}
does it like have any significance? or it is behavior which we have to take it by default?
variable/methods marked with protected modifier are visible to all the classes in the same pacakage and only to subclasses in different packages.
below are the example cases.
package a;
class A{
protected int x;
}
class B extends A{
//x can be accessed from this class
}
class C extends B {
//x can be accessed from this class
}
class D{
//x can be accesed this class but you will have to create A's instance
}
package B
class One {
//cannot access x from this class
}
class Two extends A {
//can access x from this class
}
The access level modifiers in Java are:
public - visible to all code
protected - visible to all code in the same package and to subclasses regardless of package
nothing (default) - visible to all code in the same package
private - visible only to code in the same class (including nested classes)
See, for instance, the Java tutorial Controlling Access to Members of a Class or (for lots of technical details) section 6.6 of the Java Language Specification.
Definition of the keyword
Protected
The protected modifier specifies that the member can only be accessed
within its own package (as with package-private) and, in addition, by
a subclass of its class in another package.
I suggest you read this.
The Java protected keyword works its way down to all subclasses (and members of the package). If there was a protected member in Object, any object could access it. By contrast, private is only visible to the local class (and inner classes), and public is accessible by all.
Have a look at this glossary, which shows in-depth how protected members and methods are inherited, and the Java documentation on inheritance.
You cannot restrict access to members in subclasses. This rule applies to methods (you can't override public method and make it private) but you can see analogy here. If the field is protected, it will be protected in every subclass, no matter how deep. Of course you can't override fields in Java, but just to give you an overview.
Please refer this: http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.
So if your class C shares the package with A and B, its accessible.
Inheritance is transitive: if class B inherits from class A;
and class C inherits from class B; then C is also a
subclass / child class / descendant of class A.

Is this an Instantiation of Abstract Class?

If Abstract class cannot be instantiated, then how can the variables
access and methods access of the abstract class A even without
extending is achieved in the class check (as you can see in the below
code)
Is the created a an object of abstract class A?
CODE
abstract class A
{
int a=10;
public A()
{
System.out.println("CONSTRUCTOR ONE");
}
public A(String value)
{
System.out.println("CONSTRUCTOR "+value);
}
void add(int sum)
{
System.out.println("THE SUM IS:"+sum);
}
int sub(int a,int b )
{
return(a-b);
}
}
public class check
{
public check()
{
new A("TWO"){};
}
public static void main(String args[])
{
int a,b,sum;
a=10;
b=15;
sum=a+b;
A s = new A() {};
new check();
s.add(sum);
int subb=s.sub(35,55);
System.out.println("THE SUB IS:"+subb);
System.out.println("THE VALUE OF A IS:"+s.a);
}
}
OUTPUT
CONSTRUCTOR ONE
CONSTRUCTOR TWO
THE SUM IS:25
THE SUB IS:-20
THE VALUE OF A IS:10
BUILD SUCCESSFUL (total time: 0 seconds)
The new A() {} call creates an anonymous subclass and instantiates that. Since A does not contain any abstract methods, this works.
You are creating subclass of A with this code -
A s = new A() {};
and here as well -
public check()
{
new A("TWO"){};
}
Whereas, the normal syntax for instantiation is this -
A a = new A();
which would give compilation error if you try to run this code. As such, you don't have any abstract method in your class, and hence a nominal subclass suffices and you get your code executed.
HTH,
- Manish
The normal use case is, you'd write new MyAbstractClass(){ and then implement whatever abstract methods you need to implement (and/or override existing non-abstract methods), and the compiler will infer a non-abstract subclass for you. Since your class doesn't have any abstract methods, it's not necessary to override anything.
A is marked abstract but has no abstract methods so when you do new A() {} you are providing an implementation that has nothing in it thus you are providing a concrete implementation and the class is complete.
Disregarding "visibility" (public, private, package scope, etc)... you generally need a class instance to access class members.
An exception is static classes.
Otherwise, if you have an abstract base class, you'll need to subclass to get an instance.
In your case, however, the class isn't really "abstract" (despite your attempting to label it as such). Simply because there are no abstract members or methods.
You created abstract class A without any abstract method.
Abstract classes cannot be instantiated, but they can be subclassed.
An abstract method is a method that is declared without an implementation.
In the constructor check() you just created anonymous class and call constructor A(String value).
new A("TWO"){};
This is a anonymous subclass .
1. This class create and instantiate at the same time...
2. No name of that class..
3. Because there is no name so it must need a parent .
You can get name by s.getClass().getName(); which return A$1....
A s = new A() {};
on the right side there is a new anonimus class which is inherited from A.A class haven't abstract methods so in your new anonimus class you don't need to override any methods.

Can the keyword 'this' be used in an abstract class in Java?

I tried with below example, it is working fine.
I expected it to pick sub-class's value since object won't be created for super class (as it is abstract). But it is picking up super class's field value only.
Please help me understand what is the concepts behind this?
abstract class SuperAbstract {
private int a = 2;
public void funA() {
System.out.println("In SuperAbstract: this.a " + a);
}
}
class SubClass extends SuperAbstract {
private int a = 34;
}
I am calling new SubClass.funA();
I am expecting it to print 34, but it is printing 2.
P.S.:
What I want to know is why using this in an abstract class not giving me an error?
As below text is emphasizing this would work on an instance and abstract classes won't have an instance.
Within an instance method or a
constructor, this is a reference to
the current object — the object whose
method or constructor is being called.
You can refer to any member of the
current object from within an instance
method or a constructor by using this.
from: http://java.sun.com/docs/books/tutorial/java/javaOO/thiskey.html
To answer the question in the title: Yes, this can be used in an abstract class. An abstract Animal is created at the same time as a Dog is created.
Overriding fields
You can't override fields the way you have tried it. Fields "are not virtual" like methods.
From Java Quick Reference: Overloading, Overriding, Runtime Types and Object Orientation - Overriding Methods
fields cannot be overridden but they can be hidden ie if you declare a field in a subclass with the same name as one in the superclass, the superclass field can only be accessed using super or the superclasses type
If you could, the field would probably have had to be at least protected :-)
Creation of objects of abstract classes
since object won't be created for super class (as it is abstract)
It is actually instantiated.
The abstract keyword only ensures that, when instantiated, it's instantiated in the form of a subclass. When instantiating a Dog, you're at the same time instantiating an Animal! The this reference in the context of an Animal will thus always refer to a Dog or a Cat or whatever, but in all cases it refers to some Animal. :-)
As the example below illustrates, the this reference makes sense even in an abstract class:
abstract class Animal {
public String name;
public Animal(String name) {
System.out.println("Constructing an Animal");
this.name = name;
}
public abstract void speak();
}
class Dog extends Animal {
public Dog(String name) {
super(name);
System.out.println(" Constructing a Dog");
}
public void speak() {
System.out.println("Bark! My name is " + name);
}
}
public class Test {
public static void main(String... args) {
new Dog("Woffy").speak();
}
}
Prints:
Constructing an Animal
Constructing a Dog
Bark! My name is Woffy
Update: The this reference refers to the same object in the super class as in the sub class.
You could try to add
public Animal getSuperThis() { return this; }
to the animal class, and do
System.out.println(this == getSuperThis());
in Dog.speak(). You would see that it prints true.
Any field declared in a class is unique, even if it has the same name as a a field in a base class (i.e. only methods can be overridden, but not fields). Therefore, there are two distinct fields in the derived class: SuperAbstract.a and SubClass.a. The fact that the base class is abstract has no impact.
The abstract keyword simply signifies that a class cannot be instantiated, i.e. you cannot write new SuperAbstract(). You can only instantiate object of the subclass, which must override all methods marked abstract.
The code you provided contains variable a as private member of the SuperAbstract class. Since, you don't seem to override the function, it represents the code from the SuperAbstract class, and executing it will get access to the a declared in the class itself, regardless of the fact that it is being called from any inherited class. To access the value of the later variable, you need to override the function by defining the function again in the derived class. The final code looks like this:
abstract class SuperAbstract {
protected int a = 2;
public void funA() {
System.out.println("In SuperAbstract:" + this.a);
}
}
class SubClass extends SuperAbstract {
private int a = 34;
//Overriding the above function
public void funA() {
System.out.println("In SubClass: " + a);
//Or even check using the super keyword
System.out.println("In SubClass with super: " + super.a);
//Now call the function to display the value of a from SuperAbstract
super.funA();
}
}
In the above code I changed the a to protected, so that it could be accessed from the derived class too.

Can an abstract class have a constructor?

Can an abstract class have a constructor?
If so, how can it be used and for what purposes?
Yes, an abstract class can have a constructor. Consider this:
abstract class Product {
int multiplyBy;
public Product( int multiplyBy ) {
this.multiplyBy = multiplyBy;
}
public int mutiply(int val) {
return multiplyBy * val;
}
}
class TimesTwo extends Product {
public TimesTwo() {
super(2);
}
}
class TimesWhat extends Product {
public TimesWhat(int what) {
super(what);
}
}
The superclass Product is abstract and has a constructor. The concrete class TimesTwo has a constructor that just hardcodes the value 2. The concrete class TimesWhat has a constructor that allows the caller to specify the value.
Abstract constructors will frequently be used to enforce class constraints or invariants such as the minimum fields required to setup the class.
NOTE: As there is no default (or no-arg) constructor in the parent
abstract class, the constructor used in subclass must explicitly call
the parent constructor.
You would define a constructor in an abstract class if you are in one of these situations:
you want to perform some
initialization (to fields of the
abstract class) before the
instantiation of a subclass actually
takes place
you have defined final fields in the
abstract class but you did not
initialize them in the declaration
itself; in this case, you MUST have
a constructor to initialize these
fields
Note that:
you may define more than one
constructor (with different
arguments)
you can (should?) define all your
constructors protected (making them
public is pointless anyway)
your subclass constructor(s) can
call one constructor of the abstract
class; it may even have to call it
(if there is no no-arg constructor
in the abstract class)
In any case, don't forget that if you don't define a constructor, then the compiler will automatically generate one for you (this one is public, has no argument, and does nothing).
Yes it can have a constructor and it is defined and behaves just like any other class's constructor. Except that abstract classes can't be directly instantiated, only extended, so the use is therefore always from a subclass's constructor.
Yes! Abstract classes can have constructors!
Yes, when we define a class to be an Abstract Class it cannot be instantiated but that does not mean an Abstract class cannot have a constructor. Each abstract class must have a concrete subclass which will implement the abstract methods of that abstract class.
When we create an object of any subclass all the constructors in the corresponding inheritance tree are invoked in the top to bottom approach. The same case applies to abstract classes. Though we cannot create an object of an abstract class, when we create an object of a class which is concrete and subclass of the abstract class, the constructor of the abstract class is automatically invoked. Hence we can have a constructor in abstract classes.
Note: A non-abstract class cannot have abstract methods but an abstract class can have a non-abstract method. Reason is similar to that of constructors, difference being instead of getting invoked automatically we can call super(). Also, there is nothing like an abstract constructor as it makes no sense at all.
Not only can it, it always does. If you do not specify one then it has a default no arg constructor, just like any other class. In fact, ALL classes, including nested and anonymous classes, will get a default constructor if one is not specified (in the case of anonymous classes it is impossible to specify one, so you will always get the default constructor).
A good example of an abstract class having a constructor is the Calendar class. You get a Calendar object by calling Calendar.getInstance(), but it also has constructors which are protected. The reason its constructors are protected is so that only its subclasses can call them (or classes in the same package, but since it's abstract, that doesn't apply). GregorianCalendar is an example of a class that extends Calendar.
Although there are many good answers, I would like to give my 2 cents.
Constructor DOES NOT BUILD THE OBJECT. It is used to initialize an object.
Yes, an Abstract class always has a constructor. If you do not define your own constructor, the compiler will give a default constructor to the Abstract class.
Above holds true for all classes - nested, abstract, anonymous, etc.
An abstract class (unlike interface) can have non-final non-static fields which need initialization. You can write your own constructor in the abstract class to do that. But, in that case, there won't be any default constructor.
public abstract class Abs{
int i;
int j;
public Abs(int i,int j){
this.i = i;
this.j = j;
System.out.println(i+" "+j);
}
}
Be careful while extending above abstract class, you have to explicitly call super from each constructor. The first line of any constructor calls to super(). if you do not explicitly call super(), Java will do that for you.
Below code will not compile:
public class Imp extends Abs{
public Imp(int i, int j,int k, int l){
System.out.println("2 arg");
}
}
You have to use it like below example:
public class Imp extends Abs{
public Imp(int i, int j,int k, int l){
super(i,j);
System.out.println("2 arg");
}
}
An abstract class can have a constructor BUT you can not create an object of abstract class so how do you use that constructor?
Thing is when you inherit that abstract class in your subclass you can pass values to its(abstract's) constructor through super(value) method in your subclass and no you don't inherit a constructor.
so using super you can pass values in a constructor of the abstract class and as far as I remember it has to be the first statement in your method or constructor.
Yes it can, abstract classes constructors are generally used for super calls for initialization events common to all the subclasses
Of Course, abstract class can have a constructor.Generally class constructor is used to initialise fields.So, an abstract class constructor is used to initialise fields of the abstract class. You would provide a constructor for an abstract class if you want to initialise certain fields of the abstract class before the instantiation of a child-class takes place. An abstract class constructor can also be used to execute code that is relevant for every child class. This prevents code duplication.
We cannot create an instance of an abstract class,But we can create instances of classes those are derived from the abstract class. So, when an instance of derived class is created, the parent abstract class constructor is automatically called.
Reference :This Article
Yes, Abstract Classes can have constructors !
Here is an example using constructor in abstract class:
abstract class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
// area is now an abstract method
abstract double area();
}
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
// override area for rectangle
double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);
}
// override area for right triangle
double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
class AbstractAreas {
public static void main(String args[]) {
// Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref; // this is OK, no object is created
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
}
}
So I think you got the answer.
As described by javafuns here, this is an example:
public abstract class TestEngine
{
private String engineId;
private String engineName;
public TestEngine(String engineId , String engineName)
{
this.engineId = engineId;
this.engineName = engineName;
}
//public gettors and settors
public abstract void scheduleTest();
}
public class JavaTestEngine extends TestEngine
{
private String typeName;
public JavaTestEngine(String engineId , String engineName , String typeName)
{
super(engineId , engineName);
this.typeName = typeName;
}
public void scheduleTest()
{
//do Stuff
}
}
In a concrete class, declaration of a constructor for a concrete type Fnord effectively exposes two things:
A means by which code can request the creation of an instance of Fnord
A means by which an instance of a type derived from Fnord which is under construction can request that all base-class features be initialized.
While there should perhaps be a means by which these two abilities could be controlled separately, for every concrete type one definition will enable both. Although the first ability is not meaningful for an abstract class, the second ability is just as meaningful for an abstract class as it would be for any other, and thus its declaration is just as necessary and useful.
Abstract class can have a constructor though it cannot be instantiated. But the constructor defined in an abstract class can be used for instantiation of concrete class of this abstract class. Check JLS:
It is a compile-time error if an attempt is made to create an instance of an abstract class using a class instance creation
expression.
A subclass of an abstract class that is not itself abstract may be
instantiated, resulting in the execution of a constructor for the
abstract class and, therefore, the execution of the field initializers
for instance variables of that class.
yes it is. And a constructor of abstract class is called when an instance of a inherited class is created. For example, the following is a valid Java program.
// An abstract class with constructor
abstract class Base {
Base() { System.out.println("Base Constructor Called"); }
abstract void fun();
}
class Derived extends Base {
Derived() { System.out.println("Derived Constructor Called"); }
void fun() { System.out.println("Derived fun() called"); }
}
class Main {
public static void main(String args[]) {
Derived d = new Derived();
}
}
This is the output of the above code,
Base Constructor Called
Derived Constructor Called
references:
enter link description here
Consider this:
abstract class Product {
int value;
public Product( int val ) {
value= val;
}
abstract public int multiply();
}
class TimesTwo extends Product {
public int mutiply() {
return value * 2;
}
}
The superclass is abstract and has a constructor.
Yes surely you can add one, as already mentioned for initialization of Abstract class variables.
BUT if you dont explicitly declare one, it anyways has an implicit constructor for "Constructor Chaining" to work.
Since an abstract class can have variables of all access modifiers, they have to be initialized to default values, so constructor is necessary.
As you instantiate the child class, a constructor of an abstract class is invoked and variables are initialized.
On the contrary, an interface does contain only constant variables means they are already initialized. So interface doesn't need a constructor.
In order to achieve constructor chaining, the abstract class will have a constructor.
The compiler keeps Super() statement inside the subclass constructor, which will call the superclass constructor. If there were no constructors for abstract classes then java rules are violated and we can't achieve constructor chaining.
Yes, an Abstract Class can have a Constructor. You Can Overload as many Constructor as you want in an Abstract Class. These Contractors Can be used to Initialized the initial state of the Objects Extending the Abstract Class. As we know we can't make an object of an Abstract Class because Objects are Created by the "new" keywords and not by the constructors...they are there for only initializing the state of the subclass Objects.
The purpose of the constructor in a class is used to initialize fields but not to "build objects". When you try to create a new instance of an abstract SuperClass, the compiler will give you an error. However, we can inherit an abstract class Employee and make use of its constructor by setting its variables See example below
public abstract class Employee {
private String EmpName;
abstract double calcSalary();
Employee(String name) {
this.EmpName = name;// constructor of abstract class super class
}
}
class Manager extends Employee{
Manager(String name) {
super(name);// setting the name in the constructor of sub class
}
double calcSalary() {
return 0;
}
}
package Test1;
public class AbstractClassConstructor {
public AbstractClassConstructor() {
}
public static void main(String args[]) {
Demo obj = new Test("Test of code has started");
obj.test1();
}
}
abstract class Demo{
protected final String demoValue;
public Demo(String testName){
this.demoValue = testName;
}
public abstract boolean test1();
}
class Test extends Demo{
public Test(String name){
super(name);
}
#Override
public boolean test1() {
System.out.println( this.demoValue + " Demo test started");
return true;
}
}
Yes..It is like any other class. It can have a constructor and it is called after creating object for the base class.

Categories