what is 'this' doing out here relativelayout lyt=new relativelayout(this) [duplicate] - java

This question already has answers here:
What is the meaning of "this" in Java?
(22 answers)
Closed 5 years ago.
Relativelayout lyt = new Relativelayout(this)
what is 'this' doing out here.
is that the 'this' keyword in java,if yes what's happening behind the scenes.
i just want how are we using 'this' keyword here

As you can see on the documentation, 'this' is the context. I guess this code line is on a class which extends activity, so 'this' represent the activity in which you want to insert the new layout.

You will need the Context class is when creating a view dynamically in an activity.
For example, you may want to dynamically create a ** RelativeLayout** from code. To do so, you instantiate the ** RelativeLayout** class. The constructor for the RelativeLayout class takes a Context object, and because the Activity class is a subclass of Context, you can use the this keyword to represent the Context object.

In Java, this means current object i.e. object you are currently working with.
When you say Relativelayout lyt=new Relativelayout(this) basically you are passing your current object while creating an object of Relativelayout (of course as long as Relativelayout has a contructor which accepts whatever is the type of this).
As an aside, you cannot use this in static context.
See below sample code with comments for explanation so it will be very easy for your to understand.
public class Class1 {
public static void main(String[] args) {
new Class1().test(); // see here I couldn't do "Class2 class2 = new Class2(this);" because "this" cannot be used in "static" context, so I had to create an object of Class1
}
private void test() {
Class2 class2 = new Class2(this); // here this means current object of "Class1"
}
}
public class Class2 {
private Class1 class1;
Class2(Class1 _class1){
this.class1 = _class1; // here "this" means the object of Class2.
}
}
And finally for your question about keyword, yes "this" is a keyword in Java, refer JLS specs for complete list (§3.9)

Related

Copy constructor of subclass that has its own variables [duplicate]

This question already has answers here:
how to copy SubClass object in BaseClass copy constructor
(3 answers)
Java: How to copy an object so it will be from the same subclass?
(4 answers)
Closed 4 years ago.
I have a subclass called CDAccount that has its own variables that aren't defined in the super class.
private Calendar maturityDate;
private int termOfCD;
The subclass also has a copy constructor that takes in a superclass object.
public CDAccount(Account cd){
super(cd);
}
This constructor is called by this line of code that's in a different class.
if (accounts.get(index).getType().equals("CD")) {
return new CDAccount(accounts.get(index));
}
I'm looking for a way to set the subclass variables in the copy constructor. I thought I would be able to do it with the object it takes in, because I created the object as a subclass object before setting it into the array of superclass objects.
Casting should do the trick for you:
public CDAccount(Account cd) {
super(cd);
if(cd instanceof CDAccount) {
this.maturityDate = ((CDAccount)cd).maturityDate;
this.termOfCD=((CDAccount)cd).termOfCD;
}
else {
this.maturityDate = null;
this.termOfCD= null;
}
}
This works because of the way encapsulation is implemented in Java: private variables are accessible to other instances of the same class.
The best practice would be overloading the constructor like this.
public CDAccount(CDAccount cd){
super(cd);
this.maturityDate = cd.getMaturityDate()
this.termOfCD = cd.getTermOfCD()
}
public CDAccount(Account cd){
super(cd);
}
This works for me on Java JDK v10.1

Java - What is the purpose of a "create" method that instantiates a new object? [duplicate]

This question already has answers here:
What are static factory methods?
(14 answers)
Closed 5 years ago.
Most of my experience with Java has been in the classroom setting, editing my own code. I'm finally venturing into the exciting world of deciphering other people's code, and I'm wondering about this:
public class MyClass {
// Some fields here
// A constructor there
// Setters and getters abound
public static MyClass create() {
return new MyClass();
}
}
I'm wondering what the purpose of this method is. It doesn't seem like more trouble to write MyClass foo = new MyClass(); than to write MyClass foo = MyClass.create();. Is this some kind of Java idiom I'm unaware of? Is it completely unnecessary? Would it perhaps be somehow more useful in a class where the constructor took any parameters? What's the deal?
Thanks!
It's a very useful idiom, static factory method. It gives full control on the new instance creation, whether it's a different instance, a cached instance etc. It only makes sense if the constructor is set to private.
public class MyClass {
private MyClass() {}
public static MyClass create() {
return new MyOtherClass();
}
private static class MyOtherClass extends MyClass {
...
}
}
Static factory method.
The constructor is normally private, that way the creation of new objects can be controlled by one method.
Further reading static builder class.

Confused with why private variable can be accessed? [duplicate]

This question already has answers here:
Why can I access a private variable from main method?
(7 answers)
Closed 8 years ago.
I recently see a question that what is the execution result of this code below.
public class Sandys {
private int court;
public static void main(String argv[]){
Sandys s = new Sandys(99);
System.out.println(s.court);
}
Sandys(int ballcount){
court = ballcount;
}
}
I think it can't be executed because in main i try to access a private variable.
However, this code can be perfectly executed, and the result is 99. So I am confused, why the private variable can be accessed in this code? Though the main is in Sandys class, however i create a new Sandys. Can I still access the private variable of the new Sandys object in main?
You can access private members from inside the same class, even in static methods.
main() is a special method because it is used as a starting point for java application. However, it is still a normal static method and it follows all access restrictions of static methods. Is this main() a class method? Yes, it is. Hence, it can access private members of the same class.
Consider this: if there was no access to private fields factory methods would have to be written differently.
class A {
private int a=0;
private int b=0;
private A() {}
//getters
public static A getNewInstance(int a, int b) {
A a = new A();
a.a = a;
a.b = b;
return A;
}
It does make sense, doesn't it?
You can access ALL private, protected, public and not modifier variables inside class, but you can not access private variable from another class.
P.S. It is truth also for C#, C++ and many other programming languages.
A class is defined to some particular job and in that way it may use some variables that it don't want others to access it("others" means outsider classes) and some you want other classes to access it.It all depends on your requirement.
"Private instance variables are defined to be used in only with in the class".and since in your code you are trying to access the private instance variable inside the class itself then it is perfectly legal.
Note: A static method cannot access the instance variables if u want specify the instance i mean create the instance(object) inside of the static method and access it through the created reference.

What is the proper usage of a constructor when instantiating in the main class?

The way my teacher writes and organizes code is very different than what is proposed in my supplementary textbook. In a recent lab, we were required to use the wheels library to display several objects in a single window. Here is the Snowman class that was written by my teacher (code for other objects have not been included for convenience):
public class Snowman {
private Ellipse _top;
private Ellipse _middle;
private Ellipse _bottom;
public Snowman() {
_top = new Ellipse();
_top.setColor(Color.WHITE);
_top.setFrameColor(Color.BLACK);
_top.setFrameThickness(1);
_top.setSize(80, 80);
_middle = new Ellipse();
_middle.setColor(Color.WHITE);
_middle.setFrameColor(Color.BLACK);
_middle.setFrameThickness(1);
_middle.setSize(120, 120);
_bottom = new Ellipse();
_bottom.setColor(Color.WHITE);
_bottom.setFrameColor(Color.BLACK);
_bottom.setFrameThickness(1);
_bottom.setSize(160, 160);
}
public void setLocation(int x, int y) {
_top.setLocation(x + 40, y - 170);
_middle.setLocation(x + 20, y - 100);
_bottom.setLocation(x, y);
}
}
This object, among others, is later instantiated in the SnowmanCartoon class:
public class SnowmanCartoon extends Frame{
private Snowman _snowman;
private Eyes _eyes;
private Hat _hat;
private Bubble _bubble;
public SnowmanCartoon() {
_snowman = new Snowman();
_snowman.setLocation(100, 300);
_eyes = new Eyes();
_eyes.setLocation(165, 150);
_hat = new Hat();
_hat.setLocation(152, 98);
_bubble = new Bubble();
_bubble.setLocation(280, 60);
}
public static void main(String[] args) {
new SnowmanCartoon();
}
}
Here are my concerns:
In both of these classes, why is there a method of the same name as the class, and what is its purpose?
Why is the method setLocation() a void method while the method Snowman() is not, even though Snowman() does not return anything?
In the SnowmanCartoon class, when it says private Snowman _snowman; and _snowman = new Snowman();, is Snowman referring to the Snowman class, or rather the Snowman() method?
If the instantiation of the Snowman object is referring to the Snowman() method to set all of its properties, why don't I need to use the dot operator: Snowman.Snowman()?
In my textbook, instance variables and methods are declared in a one class and are instantiated in another. However, they seem to occur simultaneously in my teacher's code.
The method that is named the same as a class is called "constructor" of the class. It is used to instantiate an object.
Example:
public class MyClass { // class
public MyClass() { // constructor
}
}
Note that constructor is just like any other method, however, it does not have a return type. It basically returns "this" object.
When you call
MyClass a = new MyClass();
this will actually invoke the constructor and create the object.
Note that you can have multiple constructors in a class by using different number and types of parameters.
In java, if you do not include any constructor, then any class will by default have the default parameterless constructor.
public MyClass() {
}
Tons of information available on constructors online. They are the basic concepts to start learning object oriented programming. Some more information here.
--EDIT--
answering question about how to call specific question.
Take these two constructors
public MyClass(){
// do things
}
public MyClass(String p){
// do things
}
Then when you instantiate object
MyClass c = new MyClass(); // use constructor 1
MyClass d = new MyClass("value"); // use constructor 2
public Snowman() {...} is called as constructor. This will be invoked while you are creating object for this class. If you don't define a constructor, jvm implicitly creates one for you. Please read this javadoc to understand more about constructors.
Snowman() is not a method, it is constructor. constructor don't have return type. If you add return type it would be treated as method.
In both of these classes, why is there a "method" of the same name as
the class?
This kind of method is called a constructor. If it takes no parameters, it is then know as the "default constructor". Constructors are what you use to build your instances ie. Snowman s = new Snowman(); calls the default constructor.
Why is the method setLocation a void method, but Snowman not one, even
though it does not return anything?
Because constructors are different than normal methods. They return an instance of their Object ie new Snowman() returns a new instance of Snowman with in its default state.
In the main SnowmanCartoon class, when it says private Snowman
_snowman; and _snowman = new Snowman();, is it referring to the Snowman class, or rather the Snowman() method?
If you ever see new Snowman() (or any equivalent), that's always referring to the constructor.
Since that is the case, why don't I need to run Snowman.Snowman() to
set all the properties, since it is a method, and not public static
void main?
When you run your program, you aren't running your classes. You're instantiating instances of your Objects to use with other operations. Saying Snowman s = new Snowman() leaves you with a Snowman Object named s so that you can now do things with that Object.
In Head First Java, instance variables and methods are declared in a
separate class, while they are instantiated in a separate class. Here,
this seems to happen at the same time, but I do not understand how.
This question doesn't make much sense to me.
In the main class, when I create a new SnowmanCartoon, why don't I
need to do something to launch it, like create the window, etc.?
This is because that class is extending Frame. Frame has default operations that are used by the base class (SnowmanCartoon). So in short your super class is taking care of this for you.
Hope that helps.
This is called constructor in java. This method is called when you do
Snowman s = new Snowman();
1 It's not a method, it's a constructor.
2 void is just a return type. void means the method does not return anything. And constructors do not have returns.
3 It's refering to Snowman() constructor. It's not a method. It creates a snowman object.
5 You can put the instantiation of snowman object in a different class. I guess your teacher put it in the same class for simplicity.
6 I am assuming JVM takes care of it.

Using "this" with class name

I am doing Android programming and was learning about Intents, when I saw a constructor that, to my C# trained mind, seemed funky. The call was:
Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
Both of the parameters are new to me. How is there a static ".this" off of a Class Name? Is this a Java thing or an Android thing? I am assuming that it is the same as just saying "this", since I am in the context of CurrentActivity, but I don't get how the "this" can be called off of the Class name itself. Also. The ".class" looks like it is used for reflection, which I am familiar with in C#, but any insight into this would be welcomed as well.
Thanks.
Usually, you can use only this. But, sometimes this makes reference to an inner class... so, for example:
Button button = (Button)findViewById(R.id.ticket_details_sell_ticket);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// it will be wrong to use only "this", because it would
// reference the just created OnClickListener object
Intent login = new Intent(ClassName.this, Login.class);
startActivityForResult(login, LOGIN_REQUEST);
}
});
One at a time:
The first construct is called a qualified this. The purpose of the syntax is in the case where you are in an inner class (typically an anonymous inner class) and you want to reference the this of the outer class rather than the this of the (anonymous) inner class. The "qualified this" can only be used in a context where this would be ambiguous. The quote the JLS "It is a compile-time error if the expression occurs in a class or interface which is not an inner class of class T or T itself".
The second construct is called a class literal is the way to reference the Class object that represents that type. It can be used in any context.
The syntax "Classname.this" is for inner classes. If you want to refer to the enclosing instance of type "Outerclass" then you do it as "Outerclass.this".
NextActivity.class is simply the Class object that describes class "NextActivity".
NextActivity.class in java means typeof(NextActivity) in C#
ClassName.this is used to reference the current instance of an outerclass from an inner class.
<ClassName>.this
is used in nested classes to refer to the current instance of the enclosing class, since the `this' keyword refers to the nest class instance.
public class Siht {
class NestedSiht {
void demoThis() {
System.err.println("this' is an instance of: " +
this.getClass().getName());
System.err.println("Siht.this' is an instance of: " +
Siht.this.getClass().getName());
}
}
void demoThis() {
new java.lang.Object() {
void demoThis() {
System.err.println("`this' is an instance of: " +
this.getClass().getName());
System.err.println("`Siht.this' is an instance of: " +
Siht.this.getClass().getName());
}
}.demoThis();
new NestedSiht().demoThis();
}
public static void main(String [] args) {
new Siht().demoThis();
}
}
It's confusing only because when you use "MainActivity.this", it seems that you are referring to the class and not the object.
In reality when you use "this" you are always referring to the current object,
as the java se documentation states:
https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
It's just syntactically peculiar.

Categories