Java - Basics of Class Instantiations and Access - java

This is a very basic question, but I'd quite like an explanation of why my question can or cannot be achieved.
If I have a class (A) which contains say a string, with a set method for that string. And I instantiate another class (B) from the first class (A), why can't I then access the first class (A) from the new class (B) to call the set method for the string in the first class (A).
The only reason I ask is that I'm working on a project with a similar problem, from a main class I create a new class which returns some buttons. And when a button is clicked the ActionListener in the main class is supposed to change the String in the initial class, but I cannot seem to access the set Method of the original class without re-instantiating the class.
Sorry if that sounds rambled, but I really want to understand why this is an issue, and what the correct way of doing it is. I know I'll probably be shot down on this, but any help is appreciated.

Because class B needs to hold a reference of the instance of A from which it has been created. There is no formal reason for which this should be made by default. For example:
public class B {
private final A creator;
public B(A creator) {
// you might want to check for non null A
this.creator = creator;
}
public void foo(String value) {
creator.setText(value);
}
}

Don't know if its the most elegant solution, but if you want object of class B to have a reference to object of class A (the creator) you can use Alessandro example code for class(B) and something like this in class A:
public class A
{
private String text;
public void createB()
{
new B(this);
}
public void setText(String b)
{
text = b;
}
}

Class cannot be called unless its been referenced by an Object. So you have to create something like this in Class B
myobject = FirstClass.new //I am not sure about java syntax as its been many years.
then you can call all the methods of FirstClass on this object and use them in SecondClass.

If B extends A, you can invoke the public methods in B that pertain to A.
If B doesn't extend A, it has no knowledge of A's methods. This is just how Java's inheritance works.

Related

Difference between pointing Interface and class ref to object?

Please read full question, Its different from this type of question
Difference between interface and class objects
Example: 1
Class implementing Interface
public interface a{
void foo();
}
public class b implements a{
#Override
void foo(){}
void bar(){}
}
Working behaviour
a asd=new b(); can call only foo()
b asf=new b(); can call both foo() and bar()
I hope upto here its clear.
Example 2:
Now there is one class CheckingPhase and IdentifyCheckingPhase
class IdentifyCheckingPhase {
private static a getPhase() {
return a;
}
private static void matchPhase(){
(CheckingPhase)IdentifyCheckingPhase.getPhase().bar();
}
}
class CheckingPhase implements a {
#Override
void foo() {
}
void bar(){
}
}
In Example 1. Interface instance only able to call its own implemented method in class and class instance able to all methods (class itself and Interface too). If that's a case, am sure something different being maintanied in compiler side that's why its able to differentiate.
Doubt First, Its correct to say that Interface and Class ref always points to different types instances of same class ? I guess yes, that's they are able to call their own methods. (Interface only its own methods but class ref can call all)
If not, Then In second example, a returned from getPhase(), should not be allowed to replace with CheckingPhase in matchPhase() and call its class instance method. Because a allowed to call only foo and CheckingPhase can call foo and bar both.
Doubt 2, I'm wondering, Is it syntactically correct using CheckingPhase instead of a while coming from method getPhase() to matchPhase() ?
I hope its clear what am trying to ask. Please let me know if may qyestion is not clear. (Its more about how java is using Syntax for above use case)

Java - method argument for any instance extending a given object

Since I don't know how to phrase my question so that I get a helping result just by searching via Google I decided to ask here. I'm just searching for a way to tell a method that it should take every Object extending a certain class. Here are the things I tried so far:
public void method( Object<? extends Component> obj );
public void method( Component c );
The problem with the second one is that i have to cast every instance to Component again before method() accepts it and the first one just didn't work for me. Can anyone give me a quick solution?
The problem with the second one is that i have to cast every instance
to Component again before method() accepts it
No, you don't have to cast anything, that's how polymorphism works.
For example:
class A {
}
class B extends A {
}
class C extends B {
}
public class Main {
private void method(final A a) {
}
public static void main(final String[] args) {
final Main main = new Main();
main.method(new B());
main.method(new C());
}
}
If you're looking to define a method that takes subtypes of Component, use public <T extends Component> void method(T t){your code here}. This will work for any object, i.e. Component can be replaced with any other class that has subclasses.
The second form public void method( Component c ); is correct, If you need to typecast then you are trying to pass as parameter a variable which type is not Component or a subclass of Component. I don't know why.
Declaring variables with type Object is not usually the right thing to do, you should define them with the correct type when you know it.
Typecast is the way to tell the compiler you know the type of the object pointed by a reference when that reference does not have that type for any reason.

How does an explicitly scoped this keyword in java work?

I know this key word is used to point to current class fields and to call constructor like:
class A{
String name;
public A(String name)
{
this.name=name;
this.(name.length());
}
public(int len)
{
//some code here
}
}
but my I recently came across:
class B extends A
{
A varA = B.this;
}
I don't understand how B.this works. can any one elaborate in detail
B.this is a reference to B class instance.
as B extends A it is possible to declare a variable of type A and assign it to a reference to B class instance.
In the example you have, B.this is equivalent to this, so it's not very illustrative. Scoped this declarations are far more valuable when you start working with inner classes....
class Outer {
public void doSomething() {
}
class Inner {
public void doSomething() {
Outer.this.doSomething();
}
}
}
Notice the use of Outer.this in the Inner class. Without it, the inner class would have no way of disambiguating between the this that referred to the Inner instance and the this that referred to the Outer instance.
In fact, the this keyword is used to refer to the instance of a class.
When you do
this.name
you are referring to the attribute name from the actual instance of the class A.
When you do
B.this
you are referring to the B class intance.
The B.this means that you are getting the reference/pointer of the B class instance, B inherits from A so what you are actually doing is Initializing your A with the reference/pointer of B.
The B.this is useful when you are calling the instance of B class inside a anonymous/inner classes.
You can also call this which is equivalent to B.this but you cant call this in a anonymous/inner classes or else you'll get the instance of them not the class B instance.

Java: Interface reference?

We all know that you can't instantiate an interface in Java (directly at least).
But with something like this:
public class Test{
public interface Link {
void mySamplemethod();
String myString ="HELLO!";
}
public static void main(String []args){
Link b;
}
}
What exactly is b... and how could it ever have a practical purpose?
b is a variable of type Link that has no value, not even null. In order to have a practical purpose you must initialize it with an object reference whose class implements Link interface.
If you want to initialize Link with a non-null value, you should create a class that implements this interface. That's mandatory in Java. If you don't want to create a new class outside this class, you can create a new class inside the class or inside the method (which would be an anonymous class). Here's a sample:
public static void main(String []args){
Link b = new Link() {
#Override
public void mySampleMethod() {
System.out.println("hello");
}
};
b.mySampleMethod();
}
The purposes of using interfaces for programming instead of direct classes is already explained very well here: What does it mean to "program to an interface"? (no need to reinvent the wheel).
You can create a reference to an interface - you just cannot instantiate it. Let's say for example you have a interface A
public interface A {
public void someMethod();
}
Now you have another class that implements this interface
public class B implements A {
public void someMethod() { // do something }
public void someOtherMethod() { // do something else }
}
Now you can have something like
A a = new B();
While a reference type A it actually implements the method as defined in B. The object type is B. The reference type A indicates that it has only access to those methods in B that are specified by A and nothing else (in this case, it has access to someMethod() and not someOtherMethod()).
What exactly is b...
b contains a reference to an instance of a class that implements Link. The reference can, of course, be null.
and how could it ever have a practical purpose?
Its practical purpose is pretty much the same as any other Java reference.
Of course, the code as it is does not really put b to any use. However, it's not hard to imagine similar code that would (you'd need to have a class that implements Link, and create an instance of that class).
For instance interfaces are widely used in polymorphism. So if you have multiple classes implementing interface, you could keep them in the same way:
class One implements Link {..}
class Two implements Link {..}
public static void main(String[] arg) {
Vector<Link> links;
Link link1 = new One();
Link link2 = new Two();
links.add(link1);
links.add(link2);
for (Link l : links) {
l.mySampleMethod();
}
}

calling derived class method using base class object

I have 6 classes as shown in figure below.
Now, class A has an object of class B as a private variable defined. Also class A methods calls many methods from class B, for example B.method1().
Now, class A_Base1 is which is derived from class A, needs to call methods from the derived class B_Base1; for example B1.method2(). And also methods of class A_Base2 needs to call methods from class B_Base2; for example B2.method3().
Now in class A I define the variable as -
private B bObject
Now in method of A_Base1, I cannot cannot call the methods like bObject.method2() since its a base class object.
I need suggestions on -
Is it possible to call derived class object methods using base class object?
Or do I need to re-design this scenario in some other good way?
Using inheritance like this imo only makes sense if the Bx.methodX() do something that means she same to the different Ax. And in that case, you should name them that way:
public class B {
public void doWhatAMeans() {
method1();
}
public class B1 extends B {
#Override
public void doWhatAMeans() {
method2();
}
public class B2 extends B {
#Override
public void doWhatAMeans() {
method3();
}
and then you only need A to call doWhatAMeans() and the A1 and A2 only need to be injected the appopriate instances of Bx.
On the other hand, if doWhatAMeans does not make sense because the methodX do different things that mean different things to Ax, then you need to rethink your object model, probably the parallel structures A,A1,A2 and B,B1,B2 are wrong then.
you could always cast. suppose your class A provides this method:
protected B getBInstance() {
return bObject;
}
then in A_Base1 you could do something like:
((B_Base1)getBInstance()).method2();
this, however, is a VERY bad design. if your A_Base1 class needs an instance of B_Base1 it should be handed such an instance directly at construction time:
public class A_Base1 extends A {
private B_Base1 b1Object;
public A_Base1(B_Base1 instance) {
super(B_Base1); //works as a B for parent
this.b1Ovject = instance;
}
}
and then you can use that
since A is a parent of A_Base1 (I'm assuming extended) you can make the function call that Accesses B public (or protected) and then A_Base1 or A_Base2 can use the same function A does to call into B.

Categories