Below is the example for Inheritance
class Parent {
Parent(int a, int b) {
int c = a + b;
System.out.println("Sum=" + c);
}
void display() {
System.out.println("Return Statement");
}
}
class Child extends Parent {
Child(int a, int b) {
int c = a - b;
System.out.println("Difference=" + c);
}
}
public class InheritanceExample {
public static void main(String args[]) {
Child c = new Child(2, 1);
c.display();
}
}
I get the below error when I don't have the non-parametrized constructor parent()
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Implicit super constructor Parent() is undefined. Must explicitly invoke another constructor
at Child.<init>(InheritanceExample.java:14)
at InheritanceExample.main(InheritanceExample.java:22)
Can you please explain me what is the purpose of the constructor without parameters in base class.
class child extends parent
{
child(int a,int b)
{
int c=a-b;
System.out.println("Difference="+c);
}
}
The first thing the child class constructor must do is call the parent class constructor.
If you do not do this explicitly (e.g. super(a,b)), a call to the default constructor is implied (super()).
For this to work, you must have this default constructor (without any parameters).
If you do not declare any constructors, you get the default constructor. If you declare at least one constructor, you do not get the default constructor automatically, but you can add it again.
The error message you are getting is complaining about the implied call to super() not working, because there is no such constructor in the parent class.
Two ways to fix it:
add a default constructor
in the first line of the child constructor, call a non-default parent constructor (super(a,b))
Also, please don't use all-lowercase class names.
The reason it is asking for parent() is because child extends parent, but you do not explicitly call super(a,b) in the child constructor. Since there is no explicit call to the parent constructor, javac tries to call the default constructor parent() and complains when it can't find it.
You can see this with this code:
class parent
{
public parent() {
System.out.println("Parent Constructor");
}
public parent(int a,int b) {
int c=a+b;
System.out.println("Sum="+c);
}
public void display() {
System.out.println("Return Statement");
}
}
class child extends parent
{
public child(int a,int b) {
int c=a-b;
System.out.println("Difference="+c);
}
}
public class InheritanceExample
{
public static void main(String args[]) {
child c=new child(2,1);
c.display();
}
}
Output:
Parent Constructor
Difference=1
Return Statement
Also, this works fine with no default constructor:
class parent
{
public parent(int a,int b) {
int c=a+b;
System.out.println("Sum="+c);
}
public void display() {
System.out.println("Return Statement");
}
}
class child extends parent
{
public child(int a,int b) {
super(a,b);
int c=a-b;
System.out.println("Difference="+c);
}
}
public class InheritanceExample
{
public static void main(String args[]) {
child c=new child(2,1);
c.display();
}
}
Output:
Sum=3
Difference=1
Return Statement
I think there was a similar question at:
Why should the derived class constructor always access base class constructor?
You can think of it this way: since "child" inherits from "parent", "child" must also be a valid instance of "parent" (polymorphism) before it can behave as a "parent" itself. As such, the very first thing "child" must do is construct itself as a valid "parent" - so a call to "parent"'s constructor via super() must be the first method call in the constructor. If no such call is present, an implicit call to the no-parameter constructor of "parent" results.
The error is there for the reason that if we do not call super explicitly then JVM puts super() in the constructor of the child class and this super() searches a constructor in parent class without parameter which is not in your class so it is wrong. Either put a non parametrised constructor in parent class or put the statement super(a,b) in the very first line of the child constructor.
class Parent
{
Parent(int a, int b)
{
int c = a + b;
System.out.println("Sum=" + c);
}
void display()
{
System.out.println("Return Statement");
}
}
class Child extends Parent
{
Child(int a, int b)
{
super(a,b);
int c = a - b;
System.out.println("Difference=" + c);
}
}
class InheritanceExample
{
public static void main(String args[])
{
Child c = new Child(2, 1);
c.display();
}
}
public class Mobile{
private String manufacturer;
private String operating_system;
public String model;
private int cost;
Mobile(String man, String o,String m, int c){
this.manufacturer=man;
this.operating_system=o;
this.model=m;
this.cost=c;
}
public String getModel(){
return this.model;
}
}
public class Android extends Mobile{
Android(String man, String o,String m, int c){
super(man,o,m,c);
}
public String getModel(){
return "This is Android mobile" +model;
}
import java.io.*;
public class XXX
{
public static void main()throws IOException
{
System.out.println("Enter your name.");
String name = in.readLine();
System.out.println(name+" rules!! Thank You!!");
}
}
Related
I have constructed a superclass and a batch of subclasses for one of my current Java projects - in this case, I want to define a function in the superclass, to be inherited by all subclasses. This function will use "this" in order to refer to the attributes in the subclasses, but this currently refers to the attributes in the SUPERclasses instead.
F.e., I have created a superclass and a subclass, where both classes have the attribute "value". A function is used to print out the value, where "this" is supposed to refer to the current class.
public class Main{
public static void main(String[] args) {
Child myObject = new Child();
myObject.printValue();
}
}
class Parent{
private int value = 10;
public void printValue(){
System.out.println(this.value);
}
}
class Child extends Parent{
private int value = 20;
}
In this case, I want to target the value in the subclass (20), by using "this" to refer to the current class. But, "this" currently refers to the "value" in the SUPERclass, resulting in the same printed message for all subclasses.
Can I set "this" to refer to the class where the function is used?
It doesn't work because fields cannot be "overridden" in subclasses. Only methods can be overridden.
You can get the effect you want if you create a getValue method replace this.value with a call to getValue.
class Parent{
private int value = 10;
public void printValue(){
System.out.println(getValue());
}
protected int getValue() {
return value;
}
}
class Child extends Parent{
private int value = 20;
#Override
protected int getValue() {
return value;
}
}
The key thing here is that "don't try to override fields of superclass" because java doesn't support that. If you have a field "value" in subclass, then discard it and use the field from superclass instead. Create a setter method in superclass to set the value or use constructor. The following code will work:
public class Main {
public static void main(String[] args) {
Child myObject = new Child();
myObject.setValue(20); // whatever value you want
myObject.printValue();
}
}
class Parent{
private Integer value = 10;
public void setValue(Integer value) {
this.value = value;
}
public void printValue(){
System.out.println(value);
}
}
class Child extends Parent{
}
If you absolutely must have a separate field "value" in subclass, honestly i think the class design is wrong. You should name the field differently (e.g "value2") because java will treat it as a different field from the one with same name in superclass. Design your code to have a childObject.setValue(value2) somewhere before calling printValue()
We will use key word this to access current class and use key word super to access superclass. We can not access subclasses in the superclass because it does not have privilege . The idea behind inheritance in Java is that you can create new classes that are built upon existing classes and have their unique properties, which are different from their parents. If you want to access superclass properties ,you need to write method in subclasses to access. If you still want to access subclass properties in superclass ,why do you make subclasses extend superclass.
public class Main{
public static void main(String[] args) {
Child myObject = new Child();
myObject.printValue();
myObject.printSuperValue();
}
}
class Parent{
private int value = 10;
public void printValue(){
System.out.println(this.value);
}
}
class Child extends Parent{
private int value = 20;
#Override
public void printValue(){
System.out.println(this.value);
}
public void printSuperValue(){
super.printValue();
}
}
Hope this can help you.
The basic answer is that, using simple variable access, there is no way to have the variable resolve dynamically relative to the concrete type of the instance which is being accessed. What variable will be resolved is based on the declared type of the instance which is being accessed. For example:
public class SampleGrandparent {
public static void main(String[] args) {
(new SampleChild(0)).printMe();
}
public int value;
public SampleGrandparent(int value) {
this.value = value;
}
public static class SampleParent extends SampleGrandparent {
#SuppressWarnings("hiding")
public int value;
public SampleParent(int value) {
super(value + 1);
this.value = value;
}
}
public static class SampleChild extends SampleParent {
#SuppressWarnings("hiding")
public int value;
public SampleChild(int value) {
super(value + 1);
this.value = value;
}
public void printMe() {
System.out.println("Child Value [ " + value + " ]");
System.out.println("Parent Value [ " + ((SampleParent) this).value + " ]");
System.out.println("Grandparent Value [ " + ((SampleGrandparent) this).value + " ]");
}
}
}
For dynamic resolution, methods will need to be used.
You can partially get around this, but only if the variables and subclass names are all known to the superclass. For example:
public class SampleGrandparent {
public static void main(String[] args) {
SampleGrandparent gp = new SampleParent(0);
gp.printMe();
}
public int value;
public SampleGrandparent(int value) {
this.value = value;
}
public void printMe() {
if ( this instanceof SampleChild ) {
System.out.println("Child Value [ " + ((SampleChild) this).value + " ]");
}
if ( this instanceof SampleParent) {
System.out.println("Parent Value [ " + ((SampleParent) this).value + " ]");
}
System.out.println("Grandparent Value [ " + value + " ]");
}
public static class SampleParent extends SampleGrandparent {
#SuppressWarnings("hiding")
public int value;
public SampleParent(int value) {
super(value + 1);
this.value = value;
}
}
public static class SampleChild extends SampleParent {
#SuppressWarnings("hiding")
public int value;
public SampleChild(int value) {
super(value + 1);
this.value = value;
}
}
}
A getter could be written in the superclass which does the same as 'printMe'.
This is all getting quite ugly, and is not advised.
One possibility you can entertain is using reflection to access the fields of the current class. The getClass method returns the actual class of the object, so for an object of the Child class it will return the Child class, even if the code is in the Parent class. You can access fields declared by that class using the getDeclaredField() method.
class Parent{
private int value = 10;
private int getValueWithReflection() {
try {
Field valueField = getClass().getDeclaredField("value");
valueField.setAccessible(true);
return valueField.getInt(this);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public void printValue(){
System.out.println(getValueWithReflection());
}
}
class Child extends Parent{
private int value = 20;
}
import java.util.*;
class A {
protected int n;
public A(int a) {
n = a;
}
protected int disp() {
return n;
}
}
class B extends A {
// what should i do here
}
public class Hello {
public static void main(String[] args) {
//Your Code Here
int a =5;
A obj= new B(a);
System.out.print(obj.disp());
}
}
What is important is that A is initialized using one of its consutructors. It is not necessary that the constructor in child class B match the parameters of the constructor(s) in A. Hence, you may define any constructor in the child class B but make sure that you call super( <some int> ) in that.
Eg, even the following is fine.
class B extends A {
public B(){ //Default constructor
super( 1 );
}
}
Also,
If you have more than one constructor in child class B, then each of them must call super( <some int> ).
If you have more than one constructor in parent class A, then in the child class constructor, calling any one of them through super( <params> ) will do.
You should do the following in B class:
class B extends A {
public B(final int a) {
super(a);
}
}
What happen here is that we're calling the constructor of our parent (A)
i want no one to override my constructor trying to use private method but it is giving my error how to stop overriding my constructor
class bc {
int a;
bc() {
System.out.println("hi this is construvtor ");
a = 10;
System.out.println("the value of a=" + a);
}
}
class dc extends bc {
int b;
dc() {
a = 20;
System.out.println("derived dc");
System.out.println("derived value of a=" + a);
}
}
public class sup {
public static void main(String[] args)
{
dc s1 = new dc();
}
}
Constructors are not overriden, methods are.
As you add a constructor in a subclass with the same parameters as which one of the parent class, it doesn't override which one of the parent.
It provides only a way to instantiate the subclass in the same way that the parent class constructor is invoked.
Using private constructor in the parent class will just make the class not inheritable as a child class constructor needs to invoke the parent constructor and the private constructor in the parent class prevents it.
Constructors can't be overridden because they are not member of class. Sub class constructor invokes super class default constructor by default. If you don't want it to be invoked, then you can make a parameterized constructor in super class and call it in subclass constructor.
class bc {
int a;
bc() {
System.out.println("hi this is construvtor ");
a = 10;
System.out.println("the value of a=" + a);
}
bc(int i){}
}
class dc extends bc {
int b;
dc() {
super(1); // invoking super class parameterized constructor
a = 20;
System.out.println("derived dc");
System.out.println("derived value of a=" + a);
}
}
public class sup {
public static void main(String[] args)
{
dc s1 = new dc();
}
}
It's correct that constructors are not overridden. But I wold like to add up some info according to your query.
You can make a constructor of the parent class private only if you have another constructor on the parent class with non-private specifier and in that case you have to call that non private super class constructor from the child class constructor using super.
N.B.: Although there is no practical use case in doing such thing. Just for the sake of your query of private constructor. Try below code:
class bc {
int a;
private bc() {
System.out.println("-----------------------");
}
private bc(int s){
System.out.println("write logic");
}
bc(int a,int b){
System.out.println("***************");
}
}
class dc extends bc {
int b;
dc(int a) {
super(8,9);
}
}
public class sup {
public static void main(String[] args)
{
new dc(9);
}
}
I have a main method in my overall parent class, outside of that main method I have two other methods that I will call inside the main method. Each of these outside methods call a method that was defined in, not the child, but the grandchild class.
Here is where I get really confused. In my big parent class, the two methods that aren't the main method take in an array that is the type of the child class. This is because each item in the array is a different type the grandchild classes. I get that because the methods that I'm calling in the parent class aren't defined in the child class (they are defined in the grandchild class) that is why they cannot be called. Is there a way to typecast the indexes to each individual grandchild class type in a for loop in the array? Or any other way?
Sorry if this is a super confusing way to phrase this question.
The normal way to do this is for the parent class to be declared abstract, and to declare that the method should exist. The grandchild class will supply a version of the method. For example:
public abstract class Doubler {
int a;
public Doubler(int a) {
this.a = a;
}
abstract int modifyResult(int aResult);
int calculate() {
int rv = a * 2;
return modifyResult(rv);
}
}
public class DoublerAndAdder extends Doubler {
int b;
public DoublerAndAdder(int a, int b) {
super(a);
this.b = b;
}
#Override
public int modifyResult(int aResult) {
return aResult + b;
}
}
calculate() is allowed to call modifyResult() even though modifyResult() is declared abstract and there is no implementation. Calling DoublerAndAdder.calculate() will run Doubler.calculate(), which will call DoublerAndAdder.modifyResult().
If you can't make the parent class abstract, the parent class can provide a version of the method which doesn't do anything:
public abstract class Doubler {
int a;
public Doubler(int a) {
this.a = a;
}
public int modifyResult(int aResult) {
return aResult;
}
int calculate() {
int rv = a * 2;
return modifyResult(rv);
}
}
The private modifier specifies that the member can only be accessed in its own class. But am I able to access it using a public method that get inherited from base class. Can someone explain me why? Does this mean object of Child class contain a member called b?
Here's the code:
package a;
public class Base {
private int b;
public int getB() {
return b;
}
public void exposeB() {
System.out.println(getB());
}
public Base(int b) {
this.b = b;
}
}
package b;
public class Child extends Base {
Child(int b) {
super(b);
}
public static void main(String args[]) {
Child b = new Child(2);
// Prints 2
System.out.println("Accessing private base variable" + b.getB());
}
}
you are not accessing the private variable in your super class directly. you are implementing the concept of Encapsulation. you are using the public getter method(in this case getB()) to make your private data accesed by other classes. thus, you can access private variable b through public getter but you never cant access b directly on its instace from another/subclass
In class Base, the field b is private but getB() is public so anybody can call that method.
What you can expect to fail compilation is something like:
System.out.println( "Accessing private base variable" + b.b );
(unless that line is called from within a method of Base itself).
You will not be able to access b directly in Child because it is private. You can, however, use the base-class's getB method which is public (and hence can be called anywhere).
To allow only extending classes and other classes in your package to access the field, you can declare it as protected.
class A {
private int n;
public A(int n) { this.n = n; }
public int n() { return n; }
}
class B extends A {
public B(int n) { super(n); }
public void print() { System.out.println(n); } // oops! n is private
}
class A {
protected int n;
public A(int n) { this.n = n; }
public int n() { return n; }
}
class B extends A {
public B(int n) { super(n); }
public void print() { System.out.println(n); } // ok
}
The private modifier means that you can't reference that field outside the class. Because getB() is public, however, you can reference that method. The getB() method can reference the private b field, because it's inside the class, and therefore can access it.
Private variable means that you can't access directly the variable from its class.... Declaring that variable private means that you can't do this
Myclass.myprivatevariable = 3
This will throw a compile error complaining that myprivatevariable is not visible fro the outside
But, as you did.... Declaring an internal method as getter or setter, public, you are allowing the user, only just through that method, to access indirectly that variable... That is always the preferred way to do.