Java: how to implement private abstract methods? - java

Is it possible to define a private abstract class in Java? How would a Java developer write a construct like below?
public abstract class MyCommand {
public void execute()
{
if (areRequirementsFulfilled())
{
executeInternal();
}
}
private abstract void executeInternal();
private abstract boolean areRequirementsFulfilled();
}

You can't have private abstract methods in Java.
When a method is private, the sub classes can't access it, hence they can't override it.
If you want a similar behavior you'll need protected abstract method.
It is a compile-time error if a method declaration that contains the keyword abstract also contains any one of the keywords private, static, final, native, strictfp, or synchronized.
And
It would be impossible for a subclass to implement a private abstract method, because private methods are not inherited by subclasses; therefore such a method could never be used.
Resources :
JLS - 8.4.3. Method Modifiers
JLS - 8.4.3.1. abstract Methods

That would be protected instead of private. It means that only classes that extend MyCommand have access to the two methods. (So do all classes from the same package, but that's a minor point.)

Related

Can I implement a Java interface method as private or protected? [duplicate]

This question already has answers here:
Why is it not allowed to narrow down scope of a method while overriding
(4 answers)
Closed 4 years ago.
Is it possible to implement an interface and then when overriding the methods, make the methods private or protected?
Interface methods are public by default (even if you don't specify it explicitly). Therefore, any method that implements an interface method must also be public, since you can't reduce the visibility of the method.
The reason:
Suppose you have an interface:
public interface SomeInterface {
public int someMethod();
}
Now you implement the interface:
public class SomeClass implements SomeInterface {
public int someMethod() {
return 1;
}
}
And you can use it as follows:
SomeInterface inter = new SomeClass();
int result = inter.someMethod();
Now, it you changed the access level of someMethod() to protected or private in the implementing class, it would no longer be accessible from outside classes (for example, in won't be accessible from a class that belongs to a different package and doesn't extend SomeClass). However, since SomeClass implements SomeInterface, and the interface's method is public, it must be accessible.
No you cannot because there are some rules(more details are mentioned here) :
In java, a method can only be written in Subclass, not in same class.
The argument list should be exactly the same as that of the overridden
method.
The return type should be the same or a subtype of the return type
declared in the original overridden method in the super class.
The access level cannot be more restrictive than the overridden
method’s access level. For example: if the super class method is
declared public then the over-ridding method in the sub class cannot
be either private or protected.
Instance methods can be overridden only if they are inherited by the
subclass.
A method declared final cannot be overridden.
A method declared static cannot be overridden but can be re-declared.
If a method cannot be inherited then it cannot be overridden.
A subclass within the same package as the instance’s superclass can
override any superclass method that is not declared private or final.
A subclass in a different package can only override the non-final
methods declared public or protected.
An overriding method can throw any uncheck exceptions, regardless of
whether the overridden method throws exceptions or not.
However the overriding method should not throw checked exceptions that
are new or broader than the ones declared by the overridden method.
The overriding method can throw narrower or fewer exceptions than the
overridden method.
Constructors cannot be overridden.

Public constructor of a private class [duplicate]

This question already has answers here:
Should we declare a public constructor when the class is declared as package private?
(2 answers)
Closed 8 years ago.
I am new to Java. I want to know what it is the use of public constructor in a private class. Private class inside the class can be initialized from the same class then what it is the use to make the constructor of private class to public?
public class MainActivity extends Activity {
private class AcceptThread extends Thread {
public AcceptThread() {
}
}
}
There doesn't seems to be any real use case for public or protected modifiers with private classes. If you have multiple classes in a single file though (but not nested or local), you need non-private constructors to instantiate the private classes.
// X.java
public class X {
private Y y = new Y();
}
class Y {
Y () {
// if this were private, X wouldn't be able to create an instance of Y
}
}
Actually default or protected visibility would be enough to create an instance in this case. All non-private modifiers allow you to create instances from other classes within the same package but practically have the same visibility.
The private class isn't visible to classes outside of the package, so public methods have no use here.
The private class can't be extended by classes outside of the package, so protected has no use either.
Even when using reflections, a public constructor is not accessible by default from other packages and will throw a IllegalAccessException. It checks the class visibility first, then the member visibility.
The default modifier is the most restrictive modifier that allows you to directly call the constructor from other classes, so package-private seems to be the most appropriate visibility for the constructor and also any other non-private methods. This also has the advantage that if you change the class visibility in the future, you don't accidentally expose the constructor or any methods to the public.
You know, I ask myself this question almost each time I make a private inner class, but I always assumed that there could be some (possibly contrived) reason for a public constructor. So #kapep 's answer got me tingling and encouraged to find ways to require a public constructor on a private inner class, but the more I think and experiment with it, the more I think the holes are plugged.
Possible angles, all of which failed me:
Serialisation: When unmarshalling an object whose superclass is not serializable, the superclass needs a no-arg constructor accessible from the subclass. So, protected should always suffice here.
Reflective tools: Code that uses reflection to get the inner class constructor through a returned instance. Fails because the type visibility is checked first, as #kapep pointed out, though it leaves a rather interesting error message:
Exception in thread "main" java.lang.IllegalAccessException: Class A can not access a member of class contrived.B$C with modifiers "public"
Inner class extension shenanigans: Don't try this at home:
package a;
class Outer {
private class Inner {
}
}
package b;
// compile error: Outer.Inner has private access in Outer
class Extender extends a.Outer.Inner {
Extender(a.Outer outer) {
outer.super();
}
}
Seemed promising at first, but I didn't get too far with that one.
In the end, I could not find a way to make a public constructor on a private inner class useful.
Then why is this technically legal despite having no use? Probably because the compiler automagically inserts a no-arg public constructor when no other constructor is provided. Hence the language should not disallow this constructs. More of an artefact than a reason, though.

Which members are not inherited in a child class?

I'm trying to answer the following question:
A child class would not inherit certain members of the parent class. Name three
such members.
I know private members are not inherited to child classes and default members are not inherited outside of the package. Can anyone complete the answer?
Edited:-
I believe that static members are inherited according to below demonstration
public class sup {
public static void main(String agr[]){
}
protected static int staticInt=0;
protected final int finalInt=3;
protected int protectedInt=0;
public String publicString = "";
private int privateInt=8;
}
class sub extends sup{
public void del(){
staticInt=1;
staticInt=finalInt;
}
}
from JLS for Class Member
Constructors, static initializers, and instance initializers are not members and therefore are not inherited.
from Oracle Java Documentation for Inheritance :
A subclass inherits all the members (fields, methods, and nested
classes) from its superclass. Constructors are not members, so they
are not inherited by subclasses, but the constructor of the superclass
can be invoked from the subclass
So I think you're missing constructors here .
Static Methods and fields are not inherited too, when they are rewritten in subclasses, they just reuse the signature and hide the implementation of the method/field in the parent class.
For Inheritance of static fields and methods, refer to this discussion as steted by Duncan, and this great tutorial Overriding vs Hiding
None-Answer to make a case for terms usage.
Members which are visible in the child class is answered above. Members being both fields and methods (each having its own namespace).
Inheritance as being part of the child instance, is another question: also invisible private members are "inherited" as such. Static members are part of the class instance and are not inherited (cannot be overriden too). All final methods cannot be overriden.
Arguable constructors are not inherited; you have to define the same signature again in a new child constructor.
Other declarations in a class could be class definitions. There the keyword static has a different meaning, and one may make obvious statements on visibility/inheritance. For instance with respect to non-static inner classes, which have an <outer-class>.this (recursive notion).
Constructors and static initializers and instance initializers.
you can't inherit a private field,and constructor.
you can't inherit a constructor because they are not member of super class. you can invoke a super class constructor form it's sub class. and you can also access a private member of super class can be accessed through public or protected method of super classes.

When i need to use a protected access modifier [duplicate]

This question already has answers here:
Java protected fields vs public getters
(8 answers)
Closed 9 years ago.
my question is concerning about the "protected" access modifier.
I know its functionality, but I don't know when I need to use it.
Conceptually methods in a class could be divided as:
constructors
setters/getters
methods used from clients (i.e other classes)
internal methods (used from other methods in the class)
You use protected when
Your class is designed for inheritance - You expect the users of your library to inherit from the class that you are designing. Very often the class will be abstract.
The class provides special functionality to its derived classes that must not be visible to other classes - You know that derived classes must have access to information that would otherwise be private, or
The derived classes must provide functionality to the base class - See Template Method Pattern for information about this use of protected methods.
Note that protected methods are similar to public methods in the sense that once you put them in, they need to stay in for as long as you support your library. Unlike private methods that you can freely remove, protected methods remain a part of the interface of your class.
Use it when you need to do some internal stuff that is not exposed in public API but still needs to be overriden by subclasses.
You need to use the protected access modifier, when you want the descendant class to see the fields / methods of the super class, BUT you do not want other classes to see these.
One situation I've found it useful in is when a superclass's method is intended to call a subclass's method, e.g.
public abstract class SuperClass
public final void exposedMethod {
hiddenMethod();
}
abstract protected void hiddenMethod();
}
public class SubClass extends SuperClass {
protected void hiddenMethod() { }
}
In this case exposedMethod takes care of things like logging and retry logic, while hiddenMethod is the actual method implementation
A lot of classes in the java api use protected constructers so that you can only have instances of objects from other objects. Example: The Graphics class. It has a protected constructor, and a way to obtain a copy of the Graphics class is to have a Image object to call getGraphics() on.
A primary usage of protected methods is when a class expects its derived classes to override the method with its own features, and also call the base class version.
E.g.
public class Base
{
public void doStuff()
{
a(); b(); c();
}
protected void a(){ //does something
}
protected void b(){ //does something
}
protected void c(){ //does something
}
}
...
public class Derived extends Base
{
protected void b()
{
// Does something different before the original functionality.
super.b(); // Calls the original functionality
// Does something different after the original functionality.
}
}
...
public class Main
{
public static void main(String args[])
{
Base b = new Derived();
b.doStuff(); // Calls b.a(), ((Derived)b).b(), b.c()
}
}
You should always encapsulate your code to restrict access to the meet the exact level of access needed. Use the protected modifier when you need to only allow access to the code within the package or when its subclassed. I don't get what you mean by...
Conceptually methods in a class could be divided as: constructors setters/getters methods used from clients (i.e other classes) internal methods (used from other methods in the class)
Just put the access modifier infront of what you need to be labeled as "protected".

Different rules for abstract methods in abstract class and interface

We cannot declare abstract methods in interface as protected and default (even if we don't mention any access specifier (default) compiler takes it as public)
but we can declare abstract method in abstract class as protected and default.
Why there are different rules for abstract class and interface?
Because abstract methods of abstract classes are meant to be hooks for subclasses. On the other hand interfaces are not concerned with implementation details - they are only about contracts with the "outside world". And a protected method is an implementation detail.
we cannot declare abstract methods in interface as protected and defaul
the purpose of Interface is to just declare contract. your client will implement it and for that it must be public.
also field in interface are public static final by default,
public you got ,static because it can't be instantiated without implementation and it must not be inherited also.
Update:
as per your question
you want to apply some strict constraint which your implementor can't see ..then what is the use of abstract method in abstract class that must be implemented by any concrete class in the inheritance hierarchy...then no one will be concrete class
public class BaseAbstractClass {
private Connection getConnection(){
//somecode
}
public boolean save(){
//get connection and do something
//return ;
}
//your implementor is left to implement it , he can use save method but can'ge see what it does i mean i doesn't have access to getConnection
public abstract void saveEntity();
}

Categories

Resources