Submit Java code for parent and child classes for the class Tree (the kind with
ID: 673329 • Letter: S
Question
Submit Java code for parent and child classes for the class Tree (the kind with leaves). Give a short explanation for why the classes you are proposing are in good parent-child relationships. Each class with one constructor, one attribute, getter and setter for the attribute, and one additional method.
Explain is-a relation with reference to your example.
Explain has-a relation with reference to your example.
Explain purpose of getter and setter method and constructor with reference to your example.
Create a static method in sub class and explain the purpose.
Explain the purpose of this keyword.
Create equals() method and explain its purpose
Explanation / Answer
public class Node
{
private Node parent;
private Object children;
private int splitAttribute;
//...
//Existing state and behaviour of Node class here
//...
public boolean alreadyHasAttribute(int attribute)
{
if (this.parent == null)
{
return false;
}
if (this.children != null && this.splitAttribute == attribute)
{
return true;
}
return this.parent.alreadyHasAttribute(attribute);
}
}
public class setget
{
private int value ;
public setget()
{
value=0 ;
}
public setget(int i)
{
this.value=i;
}
public int getvalue()
{
return value ;
}
public void setValue(int val)
{
this.value=val;
}
public static void main(String[] args)
{
setget sg= new setget(20 );
sg.setValue(20);
System.out.println(sg.getvalue());
}
}
public class SuperClass
{
public static void staticMethod()
{
System.out.println("SuperClass: inside staticMethod");
}
}
public class SubClass extends SuperClass
{
//overriding the static method
public static void staticMethod()
{
System.out.println("SubClass: inside staticMethod");
}
}
public class CheckClass
{
public static void main(String[] args)
{
SuperClass superClassWithSuperCons = new SuperClass();
SuperClass superClassWithSubCons = new SubClass();
SubClass subClassWithSubCons = new SubClass();
superClassWithSuperCons.staticMethod();
superClassWithSubCons.staticMethod();
subClassWithSubCons.staticMethod();
}
}
Below is the output which we are getting :
1) SuperClass: inside staticMethod
2) SuperClass: inside staticMethod
3) SubClass: inside staticMethod
If method is not static,
then according to polymorphism, method of the subclass is called when subclass object is passed on runtime.static method resolution is always based on the Reference type.
The code
superClassWithSuperCons.staticMethod();
superClassWithSubCons.staticMethod();
subClassWithSubCons.staticMethod();
is converted to this after compilation
SuperClass.staticMethod();
SuperClass.staticMethod();
SubClass.staticMethod();