Java method hidden but not static - java

I am trying to understand how the below prints HelloWorldExtendedHelloWorld,false. I would expect it to print "true" since the whichMethod is overridden in the ExtendedHelloWorld class. If both methods were public and static, then I think it would make more sense since then both the parent and the child method would exist and I would be calling the parent method because I am using the HelloWorld reference. In this case, however, the methods are not static - so I was expecting then to be overridden. Anyway, the parent method is private, how can it be called from the outside? Can someone please help? Thanks!
public class HelloWorld {
public HelloWorld() {
System.out.print("HelloWorld");
}
public HelloWorld(int age) {
System.out.print("HelloWorldAge");
}
private boolean whichMethod() {
return false;
}
public static void main(String[] args) {
HelloWorld example = new ExtendedHelloWorld(5);
System.out.println("," + example.whichMethod());
}
}
class ExtendedHelloWorld extends HelloWorld {
public ExtendedHelloWorld(int age) {
System.out.print("ExtendedHelloWorld");
}
public boolean whichMethod() {
return true;
}
}

You're not extending the whichMethod method and in fact can't extend it, since it's private. Also, it's not being called "externally". The main method is within the class, and so the private method is visible to main. If the main method was elsewhere, your code would not compile, since example is a HelloWorld variable, and the private whichMethod within it would not be visible.

Related

Is it possible to access objects from another class without parameters

Is it possible to access an object created in one class from another class without using parameters/arguments?
For example:
public class Main {
public static void main(String[] args) {
Two make = new Two(); // Object I created.
make.ham();
}
}
class Two {
public void ham() {
System.out.println("Ham.");
}
}
class Three {
public static void accessObject() {
// Can I access the object make here without parameters?
}
}
What I understood is that you want to access to make object, created inside Main class (Two make = new Two());. And yes, it's possible to do it.
You have to create your variable make as global and static (and it's recommended be public or protected, in case you have your classes in separate files).
So, inside your Main class, you will have to do something like:
public class Main {
public static Two make;
public static void main(String[] args) {
make = new Two(); // Object I created.
make.ham();
Three.accessObject();
}
}
As you can see, I created the make variable as static and global. This is necessary because your main method is static, and it's global to be able to be recognized by other classes. And to can call to accessObject method, I did it with the class name (because that method is static)(Three.accessObject();)
And finally inside your Three class, in the accessObject method it's necessary call to the static variable make from Main class:
class Three {
public static void accessObject() {
System.out.println("using make object from Main class in Three class...");
Main.make.ham();
}
}
As you can see now, I called the variable make with the name class Main because it's static, and finally, you will be able to call the ham method by this way.
You could you inheritance to solve your problem. For example, you would write:
class Three extends Two {
public static void accessObject() {
// You can now access the "Two" object since you have now made
// Three a subclass of Two.
}
}
EDIT:
If you wanted to say, change the implementation of the ham() method, you could do something like this:
class Two {
public void ham() {
System.out.println("Ham.");
}
}
class Three extends Two {
#Override
public void ham() {
System.out.println("I'm inside ham, but inside the Three class.);
}
}

Why is this typecasted variable calling function of subclass?

I have four classes below.
Class Note:
public class Note {
Pitch primaryPitch = new Pitch();
static Pitch secondaryPitch = new Pitch();
Note() {
System.out.println("Tune()");
}
static void pitch() {
System.out.println("Note.pitch()");
}
void volume() {
System.out.println("Note.volume()");
}
}
Class Tune:
public class Tune extends Note{
Tune() {
System.out.println("Tune()");
}
static void pitch() {
System.out.println("Tune.pitch()");
}
void volume() {
System.out.println("Tune.volume()");
}
void rhythm()
{
Note note = (Note) this;
note.volume();
}
}
Class Song:
public class Song extends Tune{
void volume() {
System.out.println("Song.volume()");
}
}
Class Test:
public class Test {
public static void main(String[] args) {
Note note2 = new Song();
((Tune)note2).rhythm();
}
When I run main, I expect the output Note.volume(). The reason I expect that output is because in the Tune class, when I call note.volume();, note has been typecast to a Note object, so I expect to use the Note class volume() method call. Instead I get Song.volume() which means I am using the Song class volume() method call.
My question is, why do I get Song.volume() and not note.volume();?
Because note is an object of type Song(). The fact that you cast it to a parent type does not change the polymorphic behavior of the volume() method. This is evident if you run the code in your IDE, and in Tune.Rhythm(), look at the variable values:
this means current instance Song, even you cast to Note, it's still Song instance
by the way, In the runtime, Java doesn't have type, so cast in the runtime is meaningless. cast is just fro Compiler to infer type by context.
Since Song also extends from Note by extends from Tune,
and Override volume method, so this.volume() will invoke the Override Song.volume method.
And if need to call the parent class Note.volume, need to use super with volume method, like: super.volume().

The method of an anonymous class behaves unexpectedly

public class Solution {
private String name;
Solution(String name) {
this.name = name;
}
private String getName() {
return name;
}
private void sout()
{
new Solution("sout")
{
void printName()
{
System.out.println(getName());
}
}.printName();
}
public static void main(String[] args) {
new Solution("main").sout();
}
}
The method of an anonymous class behaves unexpectedly.
How to make method sout to print "sout", now it prints "main"?
The problem is that String getName() is private.
What this means is that it is inaccessible to methods of derived classes.
However, the anonymous derived class is not only derived, but it is also an inner class. As such, the class has access to private members of the outer class. That is why main gets printed, not sout.
All you need to do to make this work is to make the method non-private: default access, protected, or public would work fine.
Demo.
You would use
System.out.println(super.getName());
You have an anonymous inner class Solution inside a Solution, so getName() implicitly refers to the outer instance because the method is private.
You could also make getName protected instead of private.
The explanation is a bit ornery. getName is visible to the anonymous class because of scope, but since it's private, the anonymous class can't normally refer to getName on itself because it's actually a subclass.
The really strange case of this is when you have a static nested subclass:
class Example {
private void sayHello() {
System.out.println();
}
static class Subclass extends Example {
Subclass() {
// This is a compiler error
// because it tries to call sayHello()
// on an enclosing instance which doesn't
// exist (as if Subclass is an inner class).
sayHello();
}
}
}
I walked through the specification in my answer to a question asking about the static case, which also explains why "main" gets printed here: https://stackoverflow.com/a/28971617/2891664.

android accessing object inside extended class

I have some problems using this keyword. If I have a couple of classes implementing another class, how can I use their values without calling the class itself? I explain.
//this is my first class
public class Foo extends FooHelper{
public int fooInt;
public String fooString;
//getter/setter below
}
//this is my second class
public class Foo2 extends FooHelper{
public double fooDouble;
public float fooFloat;
}
//this is my main method, i'm using it for calling the value.
//I omit all the thrash code before.
//This is how i want to call the method:
//imagine before there are onCreate, activity,...
Foo foo = new Foo().GetFooInt();
//this is the class extended from the firsts
public class FooHelper{
public void GetFooInt(){
//here is my problem, i need to call the Foo class and the fooInt value.
//I want also to be able to edit the Foo object, for example:
if(((Foo)this).getFooInt() == 0){
(Foo) this.setFooInt(5);
}
}
}
This is what i want to achieve, acces a class which extends another class with the only this keyword from the extended class. How can I do it?
EDIT:
I badly explained i think.
My problem is that i want to access my Foo object inside the FooHelper, not FooHelper's method inside Foo object.
Example:
after using this code:
Foo foo = new Foo();
foo.HelperClassMethod();
I need (in HelperClass) to access Foo object which invoked it.
public HelperClass<Foo> {
public void HelperClassMethod(){
//HERE i need to use the "foo" object which invoked this method
}
}
I added the <Foo>, probably I was missing it, is this correct? and how can i use this foo object in the method from the helper class? thanks all
EDIT2: i totally failed on my question i thinkm lets ignore the above code and just check below:
I Have to access an object inside the extended class's method.
I have this class:
public class Foo extends FooToExtend{
public int fooInt;
}
the class which is extended is this:
public class FooToExtend{
public void MethodOne(){
//HERE i need to access the calling object
}
}
now, in my main activity, I want to do this:
Foo foo = new Foo();
foo.MethodOne();
My doubt is how i can access foo object i created in main inside my MethodOne.
I have to change my FooToExtend in
public class<Foo> FooToExtend{
...
}
but I don't still know how to access the foo object inside it.
I see 2 problems here, understanding this keyword, and extending clases
PROBLEMS WITH this KEYWORD
Imagine you have a class and you are executing some code: keyword this refers to the class itself, if you where the object this would be the equivalent to me. Check here and here longer explanations, examples and tutorials.
PROBLEMS WITH extend
Also you must extend from top (interfaces or abstract classes) to bottom (extended) classes and implement in bottom part:
//this is the PARENT (FIRST) class extended from the CHILDREN (SECOND)
public abstract class FooHelper{
public abstract void GetFooInt();
}
//this is the CHILD (SECOND!!!) class
public class Foo extends FooHelper{
public int fooInt;
public String fooString;
#Override
public void GetFooInt() {
// are you sure you getFooInt method can return a null???
if(this.getFooInt() == null){
this.setFooInt(5);
}
//getter/setter below
}
EDIT 1
Oh ok, this was useful. one more question, a way is to use abstract, as you said, but is there a way to do the same without implementing it all times? just for info, my objective is to use Foo.FooHelperMethod() and be able in "FooHelperMethod()" to access Foo class. I hope i explained it, i don't know how to do it.. if it's impossible i will use abstract as you suggested :)
Sure, this is inheritance, simply don't declare abstract the parent, and implement the methods AND the attributes there, all the children will have this methods and attributes by extending the parent class.
Lets see this example:
//this is the PARENT (FIRST) class extended from the CHILDREN (SECOND)
class FooHelper {
int theIntCommonValue;
public int getTheIntCommonValue() {
return theIntCommonValue;
}
public void setTheIntCommonValue(int theIntCommonValue) {
this.theIntCommonValue = theIntCommonValue;
}
}
// CHILDREN CLASS, look how calling this.getTheIntCommonValue() (the parent method)
// doesn't throw any error because is taking parent method implementation
class Foo extends FooHelper {
public void getFooInt() {
if (this.getTheIntCommonValue() == 0)
this.setTheIntCommonValue(5);
}
}
class Foo2 extends FooHelper {
public void getFooInt() {
if (this.getTheIntCommonValue() == 3)
this.setTheIntCommonValue(8);
}
}
EDIT2:
My doubt is how i can access foo object i created in main inside my MethodOne.
ANSWER:
Passing the object as a parameter. But then, you need static class, not an extended one, lets see an
EXAMPLE:
Foo.java
public class Foo {
public int fooInt;
}
FooHelper.java
public static class FooHelper {
public static void methodOne(Foo foo){
//HERE i need to access the calling object
// for example, this?
if (foo.fooInt == 2)
}
}
Now, how do you execute it?
Main.java
public static void main(String[] args) throws Exception {
Foo foo = new Foo();
FooHelper.methodOne(foo);
}
NOTES
conventions say, methods in java start in LOWECASE and class name starts in UPPERCASE.
you must put both classes in sepparated files in order to allow static public class
I'm not sure I completely understand. But it looks as though you want GetFooInt to perform something differently depending on the class that extended it. So I think the best here to check the instanceof.
public class FooHelper{
public void GetFooInt(){
if(this instanceof Foo)
{
((Foo) this).fooInt = 5;
}
}
}
By the situation you want to named one class "Helper" I assume you will use it as a helper-class.
public class Helper {
public static int screenHeight = 500;
}
public class AnyOtherClass {
testSomething() {
System.out.println(Helper.screenHeight);
Helper.screenHeight = 510;
System.out.println(Helper.screenHeight);
}
}
For some basic understanding: this is the keyword you use in a non-static context to access the variables and methods of the Object you're currently inside. Proper use of this example:
public class SomeClass {
private int someInt;
public void setSomeInt(int someInt) {
this.someInt = someInt;
}
}
In this example the this is necessary because the local variable (/parameter) someInt has the same name as the global class variable someInt. With this you access the class varaible of the Object you're "in".
Example of unnecessary use of this:
public class SomeClass {
private int someInt;
public int squareSomeInt() {
return this.someInt * this.someInt;
}
}
Here you don't need the keyword this since there is no local variable called someInt.
On the other hand super is a keyword which accesses the variables and methods of the parent class (the class, your class is derrived from). Example:
public class SomeClass {
private int someInt;
public int squareSomeInt() {
return someInt * someInt;
}
}
the derrived class:
public class Other extends SomeClass {
public int squarePlusSquare() {
return super.squareSomeInt() + super.squareSomeInt();
}
}

Why can I inherit final method from inner class?

I discovered that following code compiles:
class Ideone
{
public static void main (String[] args){
new Ideone().m();
}
final private void m(){
System.out.println("private final method");
}
class A extends Ideone{
public void method(String [] args){
m();
}
}
}
and executes.
I am very wondering about this.
Can you explain why does java designers(founders) made that it works?
A final method can be inherited by a sub class regardless the sub class is outside the parent class or inside the parent class. But you cannot override the final method in your subclass. If the final method is private you cannot inherit that in your subclass unless your subclass is inside the parent class (like in your example).
Since you declare the method private, then final has no effect and is redundant.
Overriding a private method don't really make much sense.
It is no different then calling a private method in a class from another method in the same class (which might be public). That is something that is done often to keep code more readable and method's manageable in size.
I don't think it is a stupid question :)
Take the Builder-pattern for example. It utilizes private constructors to make sure the class is constructed the correct way. So understanding what you have available in different scope's, and why is important :)
class Ideone {
private String m;
private Ideone(String m) {
System.out.println("Build me with: " + m);
this.m = m;
}
public String getM() {
return m;
}
static class IdeoneBuilder{
String m;
public IdeoneBuilder withM(String m) {
this.m = m;
return this;
}
public Ideone build() {
return new Ideone(this.m);
}
}
public static void main (String[] args){
// new Ideone(); // will not compile
Ideone ideone = new IdeoneBuilder()
.withM("test").build();
}
}
Edit: You can make the class Ideone final, and it will still work. And you are also making it impossible to subclass it. In other words, you make sure there is no other way to construct an object of your class other than using the builder (unless the use of reflection).

Categories