Accessibility of variables and functions within my classes - java

I have 2 questions, but they are about the same (similar?) problem.
First question:
public class A {
public void myProcedure() {
doSomethingA();
}
private void doSomethingA() {}
}
public class B extends A {
#Override
public void myProcedure() {
doSomethingB();
// IT DOESN'T CALL super.myProcedure
}
private void doSomethingB() {}
}
public class C extends B {
#Override
public void myProcedure() {
// I need to execute A's myProcedure here
}
}
How to run A's myProcedure, without setting doSomethingA to public?
Second question:
I create my own TextBox, there is a variable named myValue. Now I create an AdvancedTextBox that inherits TextBox, and AdvancedTextBox need to access myValue variable. The problem is, I want future developer using both TextBox and AdvancedTextBox, or inherit them can't access myValue. Is it possible?
EDIT: Oli Charlesworth and NullUserException ఠ_ఠ tell me to let C inherit A directly (first question). However, there's some cases this can be disaster. For example: A = TextBox, B = AdvancedTextBox, C = NumberAdvancedTextBox, if C inherits A, so C have to do everything that B does again, with some small changes.

How about this ...
Put A and C in the same package, and then put B in a different package.
Remove "private" from A.doSomethingA()
Give C an instance of A. ( Favor Composition Over Inheritance )
Since C and A are in the same package, C can call A.doSomethingA() anytime.
Here is definition of A
package ac;
public class A {
public void myProcedure() {
doSomethingA();
}
void doSomethingA() {}
}
Here is definition of B
package b;
public class B extends A {
#Override
public void myProcedure() {
doSomethingB();
// IT DOESN'T CALL super.myProcedure
}
private void doSomethingB() {}
}
Here is definition of C
package ac;
// do you really need to extend B?
public class C {
A a = new A();
public void myProcedure() {
a.doSomethingA();
}
}

Since doSomethingA is an implementation detail. I would change it from a private to protected to allow subclasses to call it directly.

If some outside module calls A.myProcedure, it is not necessary for doSomethingA to be public. The other module is not calling doSomethingA directly, and that's all that matters. The deliberate intention of Java scope modifiers is that they only apply when you call a function DIRECTLY, not indirectly via another function. This way a class can have a small number of public functions that define the public interface. This can be carefully documented and very stable. Then these public functions can call any number of private functions, and you can freely shuffle these private functions around, say to improve performance, or to work with a new environment, etc, without having to change the public interface.

Related

How can I make classes implement an interface and print their methods based on a given parameter in Java?

I think this might be a very basic Java question, and I apologize since I'm a beginner, but I want to understand what am I getting wrong here: I'm supposed to create a package, and inside it, I must create the following:
an interface with a method (the question says nothing besides it, so I created it empty)
2 classes, A and B, which must implement the method created in said interface and print their own names
A third class, C, which must override B's implementation
And an Execute method inside the main class. This method must receive a letter as a parameter, no matter if it's capital case or not, and execute the method of the corresponding class (i.e. if this method receives as a parameter the letter A, it must execute the method belonging to class A)
So far I came up this this, but the code receives the input, and doesn't do anything:
Interface
public interface Test {
public static void testInterface() {
}
}
Classes
public class Teste {
public static void main(String[] args) {
class A implements Test {
public void testInterface() {
System.out.println("A");
}
}
class B implements Test {
public void testInterface() {
System.out.println("B");
}
}
class C extends B {
public void testInterface() {
System.out.println("C");
}
}
Scanner inputLetter = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter a letter from A to C: ");
String resLetter = inputLetter.nextLine(); // Read user input
if (resLetter == "A") {
A a = new A();
a.testInterface();
}
if (resLetra == "B") {
B b = new B();
b.testInterface();
}
if (resLetra == "C") {
C c = new C();
c.testInterface();
}
}
}
To be quite honest, I may be messing up with the code's structure too, since I'm not too sure of how should I organize it - I didn't create the Execute method because I had a lot of trouble creating classes without the main method, and couldn't put a method inside another, and I want to make it as simple as possible to make it work before I can try bolder things, so any help will be of great value!
You're on a good way. I'll just post some information to get you over your current roadblock.
public interface MyTestInterface {
void testInterface();
}
Interfaces will just "announce" a method. This just tells you (and the compiler) that any Class that implements MyTestInterface has to supply a method called testInterface(). Don't make them static, as this would prevent any class implementing the interface from overriding the method.
Put your classes in their own .java file. While you can define a class within a class (so called Inner Class), it has some implications.
A.java
public class A implements MyTestInterface {
#Override
public void testInterface() {
// Objects of Class A do something here
}
}
MyMain.java
public class MyMain {
public static void main(String[] args) {
MyTestInterface implementedByA = new A();
implementedByA.testInterface();
}
}
Since it implements MyTestInterface, an Object of Class A is both an instance of A and an instance of MyTestInterface. This allows you, to declare a variable of type MyTestInterface and assign it an implementation of one implementing class.
And as #Amongalen mentioned: How do I compare strings in Java?

How to use methods from extended class on objects from main class? [JAVA]

I'm starting with developing something, and I have few classes that are using the same methods, so I want to have it in one class (to easy fixing in one place etc). Problem is that I dont know how to use methods from different classes on object in main class. Code for explanation:
public class A extends C {
public UiDevice device;
device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
public void test(){
methodFromC();
}
}
public class B extends C {
public UiDevice device;
device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
public void test(){
methodFromC();
}
}
public class C {
protected void methodFromC(){
device.something();
}
}
I know that I can do it by adding argument to methodFromC:
public class C {
protected void methodFromC(UiDevice device){
device.something();
}
and running it by
methodFromC(device);
But maybe is there better solution?
First of all, as a beginning programmer unless you are doing it for school, avoid extending classes. It ends up a big spaghetti mess until you learn to moderate it (I fell for this one big-time), What you are trying to do isn't good code right now.
I THINK what you are trying to do, however is something like this:
(Assume unspecified code remains pretty much as it is)
class A extends C
{
public UiDevice getDevice()
{
return device;
}
}
abstract class C
{
public abstract UiDevice getDevice();
public methodFromC()
{
getDevice().doSomethingToDevice();
}
}
This pattern allows you to access something from A in a parent class.
B can also have it's own device. I believe this is what you are after (C being able to operate on A's device or B's device depending on which one extended C).
Get rid of the public variable.
You can use the super keyword to access anything from the class you are extending. In your case :
public class B extends C {
public UiDevice device;
device = super.methodFromB();
public void test(){
methodFromB();
}
}
If many of your classes declare methods that do the same thing, you can make them inherit from one class, let's call it class A. In class declare and implement the method. Then in child classes declare methods and in their body write:
super.nameOfYourMethodFromParentClass();
In general, to use a method from different class you just create an object of the class and call a method on it. Like:
class A {
public void myMethod() {
B b = new B();
b.methodFromB();
}
}
When it comes to inheritance be aware of this:
You can create an object of a class that declares this method or of a class that inherits from the class that declares this method and call the method on this object.
Like:
Class A inherits from C. In class C you have method methodFromC() declared. To invoke method from class C on object from class A you can do:
A a = new A();
a.methodFromC(device);
The invoked method here is the method from class C.
But if in class A you override method from class C (that means in class A you declare a method that has the same name and parameters as method in class C), then by executing the code I have written above you will invoke the method from class A, not class C.

Can an overriding method have a different access specifier from that in the base class?

Which access modifier, in an abstract class, do I have to use for a method,
so the subclasses can decide whether it should be public or not? Is it possible to "override" a modifier in Java or not?
public abstract class A {
??? void method();
}
public class B extends A {
#Override
public void method(){
// TODO
}
}
public class C extends B {
#Override
private void method(){
// TODO
}
}
I know that there will be a problem with static binding, if
someone calls:
// Will work
A foo = new B()
foo.method();
// Compiler ?
A foo = new C();
foo.method();
But maybe there is another way. How I can achieve that?
It is possible to relax the restriction, but not to make it more restrictive:
public abstract class A {
protected void method();
}
public class B extends A {
#Override
public void method(){ // OK
}
}
public class C extends A {
#Override
private void method(){ // not allowed
}
}
Making the original method private won't work either, since such method isn't visible in subclasses and therefore cannot be overriden.
I would recommend using interfaces to selectively expose or hide the method:
public interface WithMethod {
// other methods
void method();
}
public interface WithoutMethod {
// other methods
// no 'method()'
}
public abstract class A {
protected void method();
}
public class B extends A implements WithMethod {
#Override
public void method(){
//TODO
}
}
public class C extends B implements WithoutMethod {
// no 'method()'
}
... then only work with the instances through the interfaces.
When overriding methods, you can only change the modifier to a wider one, not vice versa. For example this code would be valid:
public abstract class A {
protected void method();
}
public class B extends A {
#Override
public void method() { }
}
However, if you try to narrow down the visibility, you'd get a compile-time error:
public abstract class A {
protected void method();
}
public class B extends A {
#Override
private void method() {}
}
For your case, I'd suggest to make C not implementing A, as A's abstraction implies that there's a non-private method():
public class C {
private void method(){
//TODO
}
}
Another option is to make the method() implementation in C throwing a RuntimeException:
public class C extends A {
#Override
public void method(){
throw new UnsupportedOperationException("C doesn't support callbacks to method()");
}
}
What you are asking for is not possible for very good reasons.
The Liskov substitution principle basically says: a class S is a subclass of another class T only then, when you can replace any occurrence of some "T object" with some "S object" - without noticing.
If you would allow that S is reducing a public method to private, then you can't do that any more. Because all of a sudden, that method that could be called while using some T ... isn't available any more to be called on S.
Long story short: inheritance is not something that simply falls out of the sky. It is a property of classes that you as the programmer are responsible for. In other words: inheritance means more than just writing down "class S extends T" in your source code!
This is impossible because of the polymorphism. Consider the following. You have the method in class A with some access modifier which is not private. Why not private? Because if it was private, then no other class could even know of its existence. So it has to be something else, and that something else must be accessible from somewhere.
Now let's suppose that you pass an instance of class C to somewhere. But you upcast it to A beforehand, and so you end up having this code somewhere:
void somewhereMethod(A instance) {
instance.method(); // Ouch! Calling a private method on class C.
}
One nice example how this got broken is QSaveFile in Qt. Unlike Java, C++ actually allows to lower access privileges. So they did just that, forbidding the close() method. What they ended up with is a QIODevice subclass that is not really a QIODevice any more. If you pass a pointer to QSaveFile to some method accepting QIODevice*, they can still call close() because it's public in QIODevice. They “fixed” this by making QSaveFile::close() (which is private) call abort(), so if you do something like that, your program immediately crashes. Not a very nice “solution”, but there is no better one. And it's just an example of bad OO design. That's why Java doesn't allow it.
Edit
Not that I missed that your class is abstract, but I also missed the fact that B extends C, not A. This way what you want to do is completely impossible. If the method is public in B, it will be public in all subclasses too. The only thing you can do is document that it shouldn't be called and maybe override it to throw UnsupportedOperationException. But that would lead to the same problems as with QSaveFile. Remember that users of your class may not even know that it's an instance of C so they won't even have a chance to read its documentation.
Overall it's just a very bad idea OO-wise. Perhaps you should ask another question about the exact problem you're trying to solve with this hierarchy, and maybe you'll get some decent advises on how to do it properly.
Here is a part of the #Override contract.
The answer is : there isn't any possibility to achieve what you have.
The access level cannot be more restrictive than the overridden
method's access level. For example: if the superclass method is
declared public then the overridding method in the sub class cannot be
either private or protected.
This is not a problem concerning abstract classes only but all classes and methods.
THEORY:
You have the determined modifiers order:
public <- protected <- default-access X<- private
When you override the method, you can increase, but not decrease the modifier level. For example,
public -> []
protected -> [public]
default-access -> [public, default-access]
private -> []
PRACTICE:
In your case, you cannot turn ??? into some modifier, because private is the lowest modifier and private class members are not inherited.

OOP: How to force extending class to supply private method?

Example : How would I make furtherSpecificProcessing method a private method?
Reason: I would like to be able to new an object of type B or C and only have doStuff() visible to programmer. while at the same time class B and C supply the additional functionality
abstract class A
{
protected abstract void furtherSpecificProcessing();
//concrete method utilizing abstract method
public void doStuff()
{
//busy code
furtherSpecificProcessing();
//more busy code
}
public class B extends A
{
public void furtherSpecificProcessing
{
//Class B specific processing
}
}
public class C extends A
{
public void furtherSpecificProcessing
{
//Class C specific processing
}
}
I don't think you can force return type to be private for overriding method.
Access Must not be more restrictive. Can be less restrictive.
I would suggest reading method overriding rules.
Override furtherSpecificProcessing() as protected, not as public in extending classes.
Declare the method as protected instead of public in both classes B and C.
Than what you need will work :
B b = new B();
b.doStuff(); // Will do stuff
b.furtherSpecificProcessing(); // Will not compile
and the same goes for instances of class C

Java design, how do I avoid passing object down the hierarchy?!? Impossible?

I have a number of classes, please allow me to introduce them and then ask my question at the end:
I have a container class which contains two objects in a composite relationship:
public class Container{
A a;
B b;
public someMethod(){
a.getC().myMethod(b);
}
}
A and B are superclasses (or Interfaces), with subtypes that can also be the type held in the composite relationship.
A contains a member of (interface) type C:
public class A{
C c;
}
public interface C{
public void myMethod(B b);
}
public class D implements C{
public void myMethod(B b){
//This code will modify the state of object b, in class Container.
b.changeState();
}
}
public class E implements C{
public void myMethod(B b){
//This code will modify the state of object b, in class Container.
b.changeState();
}
}
My problem is that I wish to modify the state of object b from a method starting in the container class, which eventually calls code down the hierarchy, to classes D and E- calling myMethod() via dynamic binding. I want to do this because I am going to use polymorphism to run the correct myMethod() (depending on whether the type of object is D or E) and I wish to do this, rather than write IF statements.
So my problem is that it seems very bad continually passing the instance of object b down the class hierarchy to myMethod, so that I can run b-specific code to modify the state of b. Is there anything else I can do to modify b from d and e (collectively known as c)?
I can get this to work using just interfaces but without using generics- but when I added generics i had problems with types and that made me start to think if my whole design was flawed?
EDIT: I could probably do this easily just by using IF statements- but I wanted an elegant solution using polymorphism of classes D and E.
First of all, if I understood your question correctly, no instance of B is being "passed down" in your code. Dynamic dispatch will simply cause the myMethod() implementation in the actual type of a to be called with an instance of B as argument.
While it may be tedious to have to write the argument explicitly every time you implement myMethod(), there's nothing wrong with it.
The alternative is to give each subclass/implementation of A an attribute of type B. In this case, however, you would have to pass your B instance down the chain of constructors to the class that actually has your B attribute.
Your code would become:
public class A{
C c;
public A(C c) {
this.c = c;
}
public interface C{
public void myMethod(B b);
}
public abstract class CC {
protected B b;
public CC(B b) {
this.b = b;
public class D extends CC implements C {
public D(B b) {
super(b);
}
public void myMethod(){
b.changeState();
}
}
public class E extends CC implements C {
public E(B b) {
super(b);
}
public void myMethod(){
b.changeState();
}
}
And then somewhere, e.g. in Container's constructor:
b = new B();
a = new A(new E(b));
You could pass the instance of B to the constructor of E. (or use a setter). That poses issues in itself, but at least it avoids having to pass B down every time you call myMethod(), which now needs no arguments.
e.g.
somewhere inside B
E myE = new E(this);
and, inside E
final B myB;
public E(B myHigherLevelThing) {
this.myB = myHigherLevelThing;
}
public void myMethod() {
myB.changeState();
}
Use the most general interface for the declarations, I'm a little confused about your full hierarchy so there may be room for improvement there...

Categories

Resources