My understanding is that we can't override the member variable but when i am running the below program, i am getting unexpected o/p
class Parent {
String message = "parent";
void say() {
System.out.println(message);
}
}
class Child extends Parent {
String message = "child";
}
public class Test {
public static void main(String[] args) {
new Child().say();
}
}
In the o/p i am getting "parent" While we are calling the say method using child object and even there is no Parent reference.
Can anybody help me to understand it.
Thanks
The "say" method is on the parent class, not on the child. So when it call for the "message" member it looks at his own, not at the child's one. The fact that the call is make through a child class has nothing to do in it.
Indeed, the member variable is not overriden here. This is expected behavior.
EDIT :
The Java Language Specification says that "If the class declares a field with a certain name, then the declaration of that field is said to hide any and all accessible declarations of fields with the same name in superclasses, and superinterfaces of the class."
"Inherit" does not mean "copy". When you call the "say" method on a child instance, is not a "code copy" of the method that is called, but the method of the parent class, as it is defined in the parent class. And the parent class know nothing about the child variable member.
your child class is extend parent class features! so child class has say method by default and it's value (parent) because parent class say method will called when you call say method from child object. if you want to print "child" instead, you need override your say method in the child class and change that default feature, which extends from parent class.
Related
sealed class DestinationScreen(val route:String){
object Signup: DestinationScreen(route = "signup")
}
Now I am developing navigation screen above.
I don't understand this statement.
object Signup: DestinationScreen(route = "signup")
I think Signup is property. So to set it, should we write this below?
object Signup = DestinationScreen(route = "signup")
Why does not using = issue the instance and set the Signup property?
Please teach me. Thank you.
Nope. Signup is not a property. It's basically a class which extends DestinationScreen except it's a special class object which acts as a singleton and is initiated at the same point it's described. That's why you write it like that.
Why it looks like a property to you is you happen to declare it in another class (which makes it an inner class). But you can declare it outside of the class too.
More about Kotlin objects https://kotlinlang.org/docs/object-declarations.html
Sealed classes represent a class with a fixed number of subclasses. At first, you declare the parent class, for example, a class that describes Screen of your app. Then, you declare all children of this class. For example, HomeScreen and LoginScreen:
sealed class Screen
class HomeScreen : Screen()
class LoginScreen : Screen()
All subclasses can be written outside of the parent class (but must be located in the same file due to compiler limitations).
You can use the object keyword instead of class modifier in case of a class has no properties. It means that the object keyword declares a singleton class.
Because you are using inheritance, not an assigment.
A sealed class is a class which subtypes are known by the compiler so it allows you to create flow controls by type:
sealed class Result {
data class Success(val data...): Result()
data class Error(val exception...): Result()
}
So you can do:
when(val result = ...) {
is Success -> result.data
is Error -> result.error
}
Whith normal inheritance like on interfaces, open classes or abstract classes you dont know the typed thar inherit from the super type.
When you're instantiating an object of a class that inherits from a parent class the constructor calls the superclasses constructor in most langiages I know and my question is: when the superclasse's constructor is called there will effectively be an object of that type in memory, but we're creating an object of the subclass with(in this example) additional values to add to the object so how is that accomplished in memory? Is it added to the original object? Are the contents of the original object copied into a new object with space for all the variables? Or is it something completely different?
A different question that just occured to me, are class variables, like in java, kept in the data segment of the program in memory? How are classes, not the objects, stored in memory for that matter?
Thanks.
I don't really know how engine works, but I know how to test memory usage in PHP. Both scripts
class base {
public function __construct() {
}
}
$start_memory = memory_get_usage();
$object = new base;
echo memory_get_usage() - $start_memory;
and
class base {
public function __construct() {
}
}
class derived extends base {
public function __construct() {
}
}
$start_memory = memory_get_usage();
$object = new derived;
echo memory_get_usage() - $start_memory;
return the same value. It means there'is only one instance in memory, not parent + it's child, when class is extended
phpfiddles: 1st script, 2nd script
Classed are code that define its object, so they are in Code Segment of program. And all class variables are in data segment.
And when we create an object of subclass, first its parents' object are created and it is extended for subclass members. That's why subclass object has all members of its parent class.
I have a parent bean having one instance variable like below :
public Class ParentBean {
protected boolean show; // this variable will be used to show some UI component
public void action() {
// update show variable here
}
public boolean isShow() {
return show;
}
}
Is it a good design if I want to reuse the "show" variable in a child bean (to show other UI component specific to child bean ) as shown below :
public Class ChildBean extends ParentBean {
// override the action method from parent bean
public void action() {
// update show variable here
show = true /false;
}
}
In effect , show variable is being updated by "childBean" by overriding action() method.
Is this a good design practice ? Otherwise same thing has to be repeated in ChildBean to get this work done.
If you use the show variable for the same purpose in the subclass, as you seem to be doing in this example, then obviously you should reuse it, because otherwise you just end up writing the same code twice, which is contrary to the point of OOP.
In general, in OOP, it is common to override superclass methods in subclasses, as well as modifying superclass instance variables, as long as you know what the variable you are modifying is being used for (you don't want to be randomly changing instance variables in classes that you don't completely understand, or don't have access to the source of, because you don't want any unfortunate side effects), so when it's your own code, this is absolutely fine.
As a general guideline, if your options are either to copy and paste a massive hunk of code and use it unchanged, or subclass and use the superclass' instance variables or functions, it's better to subclass. Otherwise, you're missing out on the point of OOP.
Changing the value in subclass will not affect superclass variable
This is fine with respect to the design. When a subclass object is instantiated, it will have a different copy of variable. and If superclass object is instantiated it will have different copy.
It is. Having a protected variable means you are allowed to modify it into parent or children classes (remember every single instance of each class has its own property values). So, if you have some generic functionality which is valuable for all the children:
Parent class:
public void action(){
//update show variable here
show = true;
}
Appart from that, if you want to add some extra functionality in a specifical child:
Child class:
#Override
public void action(){
super.action();
//Extra functionality goes here
//You can also access parent's 'protected' fields
if (show){
System.out.println("Shown");
}
}
An example of the use:
Parent p = new Parent();
p.action();//Prints nothing
Child c = new Child();
p.action();//Prints 'shown'
I have a groovy class that looks up a method reference and then invokes it. The method being invoked is a private method. When the actual class is an instance of the child class, it throws an error that it cannot find the private method, even though it is the public method in the parent that actually calls it.
In this case, I could obviously just call pMethod2() directly and that works, but I'm trying to understand why this doesn't work as written and if there's a way to correct it so it works.
class Parent {
def pMethod1() {
def m = this.&pMethod2
m() // this call fails if the calling class is of type Child
}
private def pMethod2() {}
public static void main(String[] args) {
new Child().pMethod1();
}
}
class Child extends Parent {}
It is a bit confusing, especially if you're used to C / C++. What you get when using the ".&" operator in Groovy is not an address, but an instance of MethodClosure.
The MethodClosure object contains an owner and a delegate object, which is used when resolving the method to call. In your example, the owner and delegate object will be "this", which is an instance of Child. The method to call is simply stored as a string.
So, the assignment
m = this.&pMethod2
is just a shorthand way of writing
m = new MethodClosure(this, "pMethod2")
When you invoke the m() closure, it will try to resolve (at runtime) the method by looking for methods named "pMethod2" in the owner and the delegate objects respectively. Since the owner and delegate is an instance of Child, it will not find private methods located in Parent.
To make your example work you must make sure that the method is visible to the owner and/or delegate of the closure.
This can be done several ways, for instance by changing the access modifier of pMethod2 to protected, or by creating the closure with an instance of Parent; something like this:
m = new Parent().&pMethod2
Note that is is irrelevant that you created the MethodClosure instance in a method where pMethod2 is actually visible. It is also irrelevant that you invoke the closure in a method where it is visible. The method is not visible to the owner or delegate of the MethodClosure, which is what is being used when resolving the method.
this is just a sample code
class parent{ //abstact class
//pure virtual function
virtual fun=0;
}
class child : parent{
fun;
}
main()
{
//what should i do here,so i can add parent in vector
attach(child);
}
void attach(parent* p){
vector.push_back(p); //want to add reference of parent into vecotr
}
and i want to cast child into parent but not able
to do please any one help me?
The child instance has the type parent (and child). If you have an instance of child, there is no extra instance of parent lying around. You can use a child instance wherever a parent instance is required. There is no need to cast.
Class cast excetion :
Occurs when u try to cast a parent class into child class.
Reason: the parent class has not everything that a child class has, on the other hand a child has everything that a parent has so you can cast a child into parent.
In other words, the instance that you want to downcast must be an instance of the class that to which you are downcasting.