Is there any way to omit a variable from super class? - java

My application class uses a library that has default two variables in it.
// A class from framework:
public class SuperClass implements Serializable {
private long id;
private long version;
// getter and setter methods for these variables...
}
I should extend this class, in order to access some of the functionality of the framework.
If I extend this class to my own class like this:
public class MyClassChild extends SuperClass {
private long myprimarykey;
private String some column;
private long myversion;
// getter and setter methods for these variables...
}
As per the programming model, those two variables are also accessible.
While implementing operation that requires an Object of type SuperClass.
Is there any idea to extend that SuperClass which is not including those two variables (id, version) ?
I do not know what to do?
Any suggestions pls?
Thanks

You cannot remove these fields, but you can override the getters and setters to do something other than the default (this depends on their access modifiers, but they will probably be protected or greater). This way you can stop the external assigning of these variables, for example. If you choose this route, I would suggest that you familiarize yourself with the ways these fields are used in the superclass so that you can anticipate any knock-on behavior.

In general JPA does not let you override superclass mappings to remove attributes, but depending on your provider it may be possible to do the following:
public class MyClassChild extends SuperClass {
private long myprimarykey;
private String some column;
private long myversion;
// Override superclass mappings
#Transient
long getId() { return super.getId(); }
#Transient
void setId(long id) { return super.setId(long id); }
// etc...
}
EDIT
In addition, it is also possible to override the values of individual columns in a mapped superclass by using the #AttributeOverride annotation, e.g.
#AttributeOverride(name="id", column=#Column(name="EMP_ID"))
#Entity
public class MyClassChild extends SuperClass {
private String some column;
...
}

Nope. If you're inheriting, you get the entire class to come along. If you don't want to inherit all the fields, you're not designing a subclass.
Imagine what would happen if you could omit variables - what would inherited methods do about the now-missing state? Everything would break...

All you can do about that is to make that variable private to the super class so subclasses do not 'see' it.

When you extend a class you are supposedly adding more variables and methods, you cannot subtract.

Related

Is this the right definition of 'private' access modifier in java?

As per the link, definition says, The private modifier specifies that the member can only be accessed in its own class.
But the below code is able to access private member item of super class in sub class.
class SuperType {
private int item;
public void setItem(int item){
this.item = item;
}
public int getItem(){
return item;
}
}
public class SubType extends SuperType{
public static void main(String[] args){
SubType s = new SubType();
s.setItem(2);
System.out.println(s.getItem());
}
}
It is also understood that s.itemdoes not work, because item is not a member of SubType class.
How do i understand this definition?
Access modifiers affect direct access to that member.
SubType can get access to item indirectly, through the public getter method, which exists in SuperType and thus has access to the private item member variable.
But SubType can't directly access it, i.e. this is an error if in SubType:
s.item // error; private in SuperType
You have the definition correct and you are accessing a private field by a public accessor and mutator. What you can't do is,
s.item = 2;
which you could if item was public. Also, the fact that SubType is a sub-class of SuperType is irrelevant here. Every class can access item by it's public accessor (and mutator).
You use getter and setters methods to acces/mutate private members in a class. The getters and setters are declared as "public".
You can extend a class and inherit the parent's private members and the getters and setters to access them.
The solution or workaround is to use "Protected" access specifier that allows you to directly access/mutate the properties of a class without any getters and setter. The usage scope is only the package where the class and other classes will be. Protected doesn't require class inheritence. As long as the classes are within the same package, they can access the neighbour's protected members.
A very good explanation has been give in SO in the past - In Java, difference between default, public, protected, and private

Why its not necessary to have abstract classes to have abstract method [duplicate]

Can have an abstract class implementing all of its methods-- with no abstract methods in it.
Eg.:
public abstract class someClass {
int a;
public someClass (int a) { this.a = a; }
public void m1 () { /* do something */ }
private void m2 () { /* do something else */ }
}
What's the advantage, if any, of having such an abstract class compared to having the same class as a concrete one instead?
One i can think of is that, when i declare it as abstract, it won't be instantiated.
however, i can have the same effect by making it concrete and its constructor(s) private.
TIA.
//==================
EDIT: One other use I can think of:
it may be extending another abstract class or implementing an interface without implementing that class's abstract methods-- although it is implementing all methods of its own. for whatever it' worth.
It has a conceptual meaning: this class has a behaviour which makes no sense on its own.
Granted, it's difficult to imagine such a scenario without well-defined extension points (i.e. abstract methods), but occasionally it will be a reasonably accurate model of your problem.
You can have something like this:
public abstract class ObjectWithId {
private final String id;
public ObjectWithId( String id ) {
this.id = id;
}
public final String getId() {
return id;
}
}
And then you can extend it to declare different types of objects that have ids. Here you have a fully specified and implemented behaviour but no restriction on any other behaviours subclasses may exhibit.
Note though that a much neater way to model the same thing is to use composition instead of inheritance.
public final class ObjectWithId<T> {
private final String id;
private final T ob;
public ObjectWithId( String id, T ob ) {
this.id = id;
this.ob = ob;
}
public String getId() {
return id;
}
public T getObject() {
return ob;
}
}
But before generics were introduced (up to Java version 1.4), this wouldn't have been as elegant and obviously better than the abstract class solution because you'd have had to trade in type safety.
you can declare to implement an interface and don't provide implementation and then each child implicitly gets interface extended
you prevent to create instance of this class
you in future provide common implementation to all children
As you pointed out, you can prevent the class from being instantiated by making it's constructor private. Othere than that, there is no benefit whatsoever. This is probably supported just to provide language completeness.
We generally use Abstraction concept with inheritance
Consider using abstract classes if any of these statements apply to
your situation:
You want to share code among several closely related classes.
To answer your question,
Why declare a class with concrete methods Abstract?
One possible reason is to support inheritance without actually creating objects
Assume you have two classes one Abstract and other Concrete
Abstract class : AbsClass
abstract class AbsClass {
int a = 5;
//Constructor
public AbsClass() {
System.out.println(a);
}
void methodA() {
System.out.println(a + 10);
}
}
and
Concrete class : ConcreteClass
class ConcreteClass {
int a = 10;
//Made the constructor Private to prevent from creating objects of this class
private ConcreteClass() {
System.out.println(a);
}
void methodA() {
System.out.println(a + 10);
}
}
The above two classes should function similarly (?) Until you try to Subclass them
class AbsImplementer extends AbsClass {
//Works fine
}
class ConcImplementer extends ConcreteClass {
//Compilation Error Implicit super constructor ConcreteClass() is not visible
}
The practical difference is that you can't create an instance of it. You would have to subclass it and create an instance of the subclass.
As to WHY you would want to do this, in practice ... I'm hard pressed to think of a good reason. You could say that the class is only meaningful if someone creates a subclass that implements some function. But then why not make that function abstract in the super-class?
I wouldn't rule out the possibility that someone might come up with some example where this makes sense, but I can't think of one. Just because it's possible to write a piece of code and that code compiles successfully doesn't mean that that it makes sense. I mean, I can write "total_price = item_price * zip_code + customer_height_in_cubits - 7.879", but that doesn't mean such a line of code would be meaningful.
Well assume that you don't care whether the methods of the abstract class are implemented or abstract, but by design it has to be abstract so that when someone extends it, they have to add more methods or override the existing ones or use as is. If they don't want to override the methods then the default behavior is already provided in that abstract class.
In this abstract class, the only criteria you enforce is - one simply cannot instantiate that class and they have to have their only version of class before using it.
So in general, abstract class with few or all methods being implemented, is much better than having an interface which has no methods implemented at all. This is based on the assumption that you are using it as a single inheritance.
Consider something similar to the NVI pattern (not sure what you'd call it in Java):
public abstract class A {
public final void doSomething() {
System.out.println("required");
doOptional();
}
protected void doOptional() {
System.out.println("optional");
}
}
public class B extends A {
#Override
protected void doOptional() {
System.out.println("overridden");
}
}
For your public API, you only expose a public final method which cannot be overridden. It performs some required work inside there and an optional method. When extending this class, you can only override doOptional().
Calling B.doSomething() will always print "required" before it proceeds.
Since doOptional() is not abstract, there's no purely code reason that class A needs to be abstract. But it might be desired for your particular project. For example, a base service that is always extended into specific sub-projects.
This can be useful for cases when the classes derived from the abstract base class must have some behaviour that is different from each other but that behaviour can not be abstracted as residing within a method that has the same signature for all the classes. Being unable to share a signature can occur if the different behaviour requires methods that are passed different primitive types. Because they use primitive types you can not use generics to express the similarity.
An abstract base class without any abstract methods is acting a bit like a marker interface, in that it is declaring that implementing classes must provide some behaviour without having that behaviour encapsulated within a new method with a signature that is the same for all implementations. You would use an abstract base class rather than a marker interface when the implementing classes have some behaviour in common, especially if the base class can implement it for the derived classes.
For example:
abstract class Sender {
protected final void beginMessage() {
...
}
protected final void endMessage() {
...
}
protected final void appendToMessage(int x) {
...
}
}
final class LongSender extends Sender {
public void send(int a, int b, int c) {
beginMessage();
appendToMessage(a);
appendToMessage(b);
appendToMessage(c);
endMessage();
}
}
final class ShortSender extends Sender {
public void send(int a) {
beginMessage();
appendToMessage(a);
endMessage();
}
}
It can be useful if you consider it an utility class.

What's the point in having an abstract class with no abstract methods?

Can have an abstract class implementing all of its methods-- with no abstract methods in it.
Eg.:
public abstract class someClass {
int a;
public someClass (int a) { this.a = a; }
public void m1 () { /* do something */ }
private void m2 () { /* do something else */ }
}
What's the advantage, if any, of having such an abstract class compared to having the same class as a concrete one instead?
One i can think of is that, when i declare it as abstract, it won't be instantiated.
however, i can have the same effect by making it concrete and its constructor(s) private.
TIA.
//==================
EDIT: One other use I can think of:
it may be extending another abstract class or implementing an interface without implementing that class's abstract methods-- although it is implementing all methods of its own. for whatever it' worth.
It has a conceptual meaning: this class has a behaviour which makes no sense on its own.
Granted, it's difficult to imagine such a scenario without well-defined extension points (i.e. abstract methods), but occasionally it will be a reasonably accurate model of your problem.
You can have something like this:
public abstract class ObjectWithId {
private final String id;
public ObjectWithId( String id ) {
this.id = id;
}
public final String getId() {
return id;
}
}
And then you can extend it to declare different types of objects that have ids. Here you have a fully specified and implemented behaviour but no restriction on any other behaviours subclasses may exhibit.
Note though that a much neater way to model the same thing is to use composition instead of inheritance.
public final class ObjectWithId<T> {
private final String id;
private final T ob;
public ObjectWithId( String id, T ob ) {
this.id = id;
this.ob = ob;
}
public String getId() {
return id;
}
public T getObject() {
return ob;
}
}
But before generics were introduced (up to Java version 1.4), this wouldn't have been as elegant and obviously better than the abstract class solution because you'd have had to trade in type safety.
you can declare to implement an interface and don't provide implementation and then each child implicitly gets interface extended
you prevent to create instance of this class
you in future provide common implementation to all children
As you pointed out, you can prevent the class from being instantiated by making it's constructor private. Othere than that, there is no benefit whatsoever. This is probably supported just to provide language completeness.
We generally use Abstraction concept with inheritance
Consider using abstract classes if any of these statements apply to
your situation:
You want to share code among several closely related classes.
To answer your question,
Why declare a class with concrete methods Abstract?
One possible reason is to support inheritance without actually creating objects
Assume you have two classes one Abstract and other Concrete
Abstract class : AbsClass
abstract class AbsClass {
int a = 5;
//Constructor
public AbsClass() {
System.out.println(a);
}
void methodA() {
System.out.println(a + 10);
}
}
and
Concrete class : ConcreteClass
class ConcreteClass {
int a = 10;
//Made the constructor Private to prevent from creating objects of this class
private ConcreteClass() {
System.out.println(a);
}
void methodA() {
System.out.println(a + 10);
}
}
The above two classes should function similarly (?) Until you try to Subclass them
class AbsImplementer extends AbsClass {
//Works fine
}
class ConcImplementer extends ConcreteClass {
//Compilation Error Implicit super constructor ConcreteClass() is not visible
}
The practical difference is that you can't create an instance of it. You would have to subclass it and create an instance of the subclass.
As to WHY you would want to do this, in practice ... I'm hard pressed to think of a good reason. You could say that the class is only meaningful if someone creates a subclass that implements some function. But then why not make that function abstract in the super-class?
I wouldn't rule out the possibility that someone might come up with some example where this makes sense, but I can't think of one. Just because it's possible to write a piece of code and that code compiles successfully doesn't mean that that it makes sense. I mean, I can write "total_price = item_price * zip_code + customer_height_in_cubits - 7.879", but that doesn't mean such a line of code would be meaningful.
Well assume that you don't care whether the methods of the abstract class are implemented or abstract, but by design it has to be abstract so that when someone extends it, they have to add more methods or override the existing ones or use as is. If they don't want to override the methods then the default behavior is already provided in that abstract class.
In this abstract class, the only criteria you enforce is - one simply cannot instantiate that class and they have to have their only version of class before using it.
So in general, abstract class with few or all methods being implemented, is much better than having an interface which has no methods implemented at all. This is based on the assumption that you are using it as a single inheritance.
Consider something similar to the NVI pattern (not sure what you'd call it in Java):
public abstract class A {
public final void doSomething() {
System.out.println("required");
doOptional();
}
protected void doOptional() {
System.out.println("optional");
}
}
public class B extends A {
#Override
protected void doOptional() {
System.out.println("overridden");
}
}
For your public API, you only expose a public final method which cannot be overridden. It performs some required work inside there and an optional method. When extending this class, you can only override doOptional().
Calling B.doSomething() will always print "required" before it proceeds.
Since doOptional() is not abstract, there's no purely code reason that class A needs to be abstract. But it might be desired for your particular project. For example, a base service that is always extended into specific sub-projects.
This can be useful for cases when the classes derived from the abstract base class must have some behaviour that is different from each other but that behaviour can not be abstracted as residing within a method that has the same signature for all the classes. Being unable to share a signature can occur if the different behaviour requires methods that are passed different primitive types. Because they use primitive types you can not use generics to express the similarity.
An abstract base class without any abstract methods is acting a bit like a marker interface, in that it is declaring that implementing classes must provide some behaviour without having that behaviour encapsulated within a new method with a signature that is the same for all implementations. You would use an abstract base class rather than a marker interface when the implementing classes have some behaviour in common, especially if the base class can implement it for the derived classes.
For example:
abstract class Sender {
protected final void beginMessage() {
...
}
protected final void endMessage() {
...
}
protected final void appendToMessage(int x) {
...
}
}
final class LongSender extends Sender {
public void send(int a, int b, int c) {
beginMessage();
appendToMessage(a);
appendToMessage(b);
appendToMessage(c);
endMessage();
}
}
final class ShortSender extends Sender {
public void send(int a) {
beginMessage();
appendToMessage(a);
endMessage();
}
}
It can be useful if you consider it an utility class.

Java static methods/fields in interface (again!)

my problem is:
I have a bunch of different classes all extending a base class (Identifiable).
I need to assign to some of the sub-class a certain value (securityLevel) which should be changeable and assigned to all member of the class (i.e.: it should be static).
I need to access the classes via the common ancestor.
How do I do this?
The first thing which came to mind is to have a dedicated interface (ISecurity) defining either the values or a static method to access them and let the actual classes either not to implements it and, if they do, to override the static field (or method to retrieve it).
However this is not possible for two reasons:
The current Java language does not allow static members in interfaces.
Even if it would allow it it would not be possible to #Override it.
How can I code around the problem?
The only way I found is:
add a non-static member (public Class getValueProvider()) to base class to retrieve the value returning null.
in the interested classes #Override the non-static method returning the value of a private static Class getValueProvider() implementing setters and getters for the wanted value.
use the retrieved class instance to obtain the requested value (or skip everything if the return is null).
This is very ugly and there's no way to enforce the correct implementation in sub-classes.
You could try a service/factory type of implementation. Or have some sort of class object that stores security (SecuritySettings) and send in the current Identifiable object to get security level
public class Identifiable { }
public class SampleUser extends Identifiable { }
public class ExampleUser extends Identifiable { }
public class UserService
{
public int SampleUserSecurity = 0;
//Or an array/dictionary structure
public int GetSecurityLevel(Identifiable user)
{
if(user instanceof SampleUser)
{
return SampleUserSecurity;
}
}
public SampleUser CreateSampleUser()
{
return new SampleUser();
}
public ExampleUser CreateExampleUser()
{
return new ExampleUser();
}
}
You could define Identifiable to be an abstract class. Additionally, you can define another abstract class that extends Identifiable and adheres to your restrictions, ie holds the static variable and whatever methods may be necessary.
I would try to avoid any static members. Static members in java are always clamsy (you cannot override just hide them, etc.)
I'm not sure if I understand your problem corret but I suggest you construct the objects with a context interface or something. The objects then cann access these context interface if they area allowed to return a value or have to return a special value.
The one creating all these objects can pass the same object and so control the behaviour. This object could then be held static (like a singelton)

Can I have private final fields in abstract class

Can I create a abstract class like below..?
abstract class A{
private final String foo;
private final String too;
public A(final String foo, final String too) {
this.foo= foo;
this.too= too;
}
public String getfoo(){
return foo;
}
public String gettoo(){
return too;
}
}
Short: yes.
Long(er): an abstract class is just a class that can't be instantiated as is, since parts might still be missing. Thus i can have private fields. Just note that subclasses don't have access to them, except via the getters/setters.
Your code is correct.
Note: good practice in abstract classes is protected constructor, beacuse class itself cannot be instantiated and the inheriting classes must have to call super(...) constructor.
Yes you can.
Consider the possibility to make them protected instead of private to allow your subclasses i.e. the ones extending this class, to have direct access to the fields..
Yes of course possible.But it is not a good practice because you cant create one object of this class.Main point is that you also dont require this type of class because you have not define any abstract functions inside it. But as per your question you can definitely create this type of abstract class.

Categories