Related
I have 2 classes:
public class Animal {
protected String name;
int age;
public Animal(String name, int age) {
// TODO Auto-generated constructor stub
this.name = name;
this.age = age;
}
public static void eating() {
System.out.println("eating");
}
}
public class Human extends Animal{
public Human(String name, int age) {
// TODO Auto-generated constructor stub
super(name, age);
}
public static void talking() {
System.out.println("Talk");
}
}
main program:
public class program {
public static void main (String [] args) {
Animal hum = new Human("bob", 1);
System.out.println(hum);
//hum.talking();
}
}
The output of the main program is wk05.Human#7f690630. So why I can't do "hum.talking" in the main program? My understanding of inheritance is that the subclass can invoke the methods defined in the parent class as well as the method defined in the subclass.
Here in your program Animal hum = new Human("bob", 1); means hum reference to Animal super class which does not have definition of talking() and object is Human.
At compile time reference is considered rather than the object. Object is used at runtime. So if you want to call talking() you would need to:
1) Create reference to Human class
Here the reference is also to Human class so it has the definition of talking() method at compile time.
Human hum = new Human("bob", 1);
hum.talking();
2) Cast object to Human (only for understanding the type-casting)
When we cast the object we explicitly tell the compiler to refer the defined object. So it can refer that.
Animal hum = new Human("bob", 1);
((Human) hum).talking();
Reason behind is that let's say you have one more class SuperHuman which also extends Animal class and that class doesn't have talking() method then how the compiler would be knowing that reference hum will be referring Human or SuperHuman?
And let's say during initialization you have we have done like Animal hum = new Human("bob", 1); and later in code the hum is updated to hum = SuperHuman("sup", 10);. That's the reason compile time reference is referred and Object is referred at runtime.
The error is a compile error; the compiler doesn’t care what the object type actually is (or could be), it only cares about what it’s declared as.
Also, I’m almost certain your methods should not be static.
If you were to do something like what you’re exploring, you have to abstract out the method, either as an interface or an abstract method. For example:
class abstract Animal {
abstract void communicate();
}
class Dog extends Animal {
void communicate() {
System.out.println("bark");
}
}
class Human extends Animal {
void communicate() {
System.out.println("talk");
}
}
As Gaurav says you have to create a reference to Human or cast Animal to Human. But inheritance would make more sense if Animal were an interface or an abstract class (What I don't particularly like to do) and exposed a method in which all derived classes should have to implement.
public interface Animal {
String getName();
int getAge();
void blab();
}
public class Human implements Animal {
private String name;
private int age;
Human(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() { return name; }
public int getAge() { return age; }
public void blab() {
System.out.println("Talk");
}
}
And the main
public class Program {
public static void main(String[] args) {
Animal animal = new Human("Bob", 1);
animal.blab();
}
}
I'm very new to java and would like to know whether calling a subclass method in a superclass is possible. And if doing inheritance, where is the proper place to set public static void main.
Superclass
public class User {
private String name;
private int age;
public User() {
//Constructor
}
//Overloaded constructor
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return this.name;
}
public static void main(String []args) {
User user1 = new Admin("Bill", 18, 2);
System.out.println("Hello "+user1.getName());
user1.getLevel();
}
}
Subclass
public class Admin extends User {
private int permissionLevel;
public Admin() {
//Constructor
}
//Overloading constructor
public Admin(String name, int age, int permissionLevel) {
super(name, age);
this.permissionLevel = permissionLevel;
}
public void getLevel() {
System.out.println("Hello "+permissionLevel);
}
}
Short answer: No.
Medium answer: Yes, but you have to declare the method in the superclass. Then override it in the subclass. The method body from the subclass will be in invoked when the superclass calls it. In your example, you could just put an empty getLevel method on User.
You could also consider declaring User as an abstract class and declaring the getLevel method as abstract on the User class. That means you don't put any method body in getLevel of the User class but every subclass would have to include one. Meanwhile, User can reference getLevel and use the implementation of its subclass. I think that's the behavior you're going for here.
I'm very new to java and would like to know whether calling a subclass
method in a superclass is possible.
A superclass doesn't know anything about their subclasses, therefore, you cannot call a subclass instance method in a super class.
where is the proper place to set public static void main.
I wouldn't recommend putting the main method in the Admin class nor the User class for many factors. Rather create a separate class to encapsulate the main method.
Example:
public class Main{
public static void main(String []args) {
User user1 = new Admin("Bill", 18, 2);
System.out.println("Hello "+user1.getName());
user1.getLevel();
}
}
No, it is not possible to call sub class method inside super class.
Though it is possible to call different implementations of the same method in a client code while you have a variable with a super class type and instantiate it with either super class or sub class objects. It is called polymorphism.
Please, consider the following example:
public class User {
private String name;
private int age;
protected int permissionLevel;
public User() {
//Constructor
}
//Overloaded constructor
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return this.name;
}
public void getLevel() {
System.out.println("Hello "+ permissionLevel);
}
}
public class Admin extends User {
public Admin() {
//Constructor
}
//Overloading constructor
public Admin(String name, int age, int permissionLevel) {
super(name, age);
this.permissionLevel = permissionLevel;
}
#Override
public void getLevel() {
System.out.println("Hello "+permissionLevel);
}
public static void main(String []args) {
User user1 = new Admin("Bill", 18, 2);
System.out.println("Hello "+user1.getName());
user1.getLevel(); //call to subclass method
user1 = new User("John", 22); //the variable is the same but we assign different object to it
user1.getLevel(); //call to superclass method
}
}
Answering your second question, no, it does not matter where you place your main method as long as it is of right method signature. As you can see in my example I moved the method to Admin.java - it is still acceptable.
Calling subclass method in a superclass is possible but calling a subclass method on a superclass variable/instance is not possible.
In java all static variable and methods are considered to be outside the class i.e they do have access to any instance variable or methods. In your example above it will be wise to create a new class called Main and put public static void main in there but this is just a hygiene issue and what you have above will work except for the line.
user1.getLevel()
Use case: If employee eats, then automatically should sleep:-)
Declare two methods eat and sleep from class person.
Invoke the sleep method from eat.
Extend person in the employee class and override only the sleep method:
Person emp=new Employee();
emp.eat();
Explanation: As eat method is not in subclass, it will invoke the super class eat. From there, sub class's sleep will be invoked.
Is it possible to call a constructor from another (within the same class, not from a subclass)? If yes how? And what could be the best way to call another constructor (if there are several ways to do it)?
Yes, it is possible:
public class Foo {
private int x;
public Foo() {
this(1);
}
public Foo(int x) {
this.x = x;
}
}
To chain to a particular superclass constructor instead of one in the same class, use super instead of this. Note that you can only chain to one constructor, and it has to be the first statement in your constructor body.
See also this related question, which is about C# but where the same principles apply.
Using this(args). The preferred pattern is to work from the smallest constructor to the largest.
public class Cons {
public Cons() {
// A no arguments constructor that sends default values to the largest
this(madeUpArg1Value,madeUpArg2Value,madeUpArg3Value);
}
public Cons(int arg1, int arg2) {
// An example of a partial constructor that uses the passed in arguments
// and sends a hidden default value to the largest
this(arg1,arg2, madeUpArg3Value);
}
// Largest constructor that does the work
public Cons(int arg1, int arg2, int arg3) {
this.arg1 = arg1;
this.arg2 = arg2;
this.arg3 = arg3;
}
}
You can also use a more recently advocated approach of valueOf or just "of":
public class Cons {
public static Cons newCons(int arg1,...) {
// This function is commonly called valueOf, like Integer.valueOf(..)
// More recently called "of", like EnumSet.of(..)
Cons c = new Cons(...);
c.setArg1(....);
return c;
}
}
To call a super class, use super(someValue). The call to super must be the first call in the constructor or you will get a compiler error.
[Note: I just want to add one aspect, which I did not see in the other answers: how to overcome limitations of the requirement that this() has to be on the first line).]
In Java another constructor of the same class can be called from a constructor via this(). Note however that this has to be on the first line.
public class MyClass {
public MyClass(double argument1, double argument2) {
this(argument1, argument2, 0.0);
}
public MyClass(double argument1, double argument2, double argument3) {
this.argument1 = argument1;
this.argument2 = argument2;
this.argument3 = argument3;
}
}
That this has to appear on the first line looks like a big limitation, but you can construct the arguments of other constructors via static methods. For example:
public class MyClass {
public MyClass(double argument1, double argument2) {
this(argument1, argument2, getDefaultArg3(argument1, argument2));
}
public MyClass(double argument1, double argument2, double argument3) {
this.argument1 = argument1;
this.argument2 = argument2;
this.argument3 = argument3;
}
private static double getDefaultArg3(double argument1, double argument2) {
double argument3 = 0;
// Calculate argument3 here if you like.
return argument3;
}
}
When I need to call another constructor from inside the code (not on the first line), I usually use a helper method like this:
class MyClass {
int field;
MyClass() {
init(0);
}
MyClass(int value) {
if (value<0) {
init(0);
}
else {
init(value);
}
}
void init(int x) {
field = x;
}
}
But most often I try to do it the other way around by calling the more complex constructors from the simpler ones on the first line, to the extent possible. For the above example
class MyClass {
int field;
MyClass(int value) {
if (value<0)
field = 0;
else
field = value;
}
MyClass() {
this(0);
}
}
Within a constructor, you can use the this keyword to invoke another constructor in the same class. Doing so is called an explicit constructor invocation.
Here's another Rectangle class, with a different implementation from the one in the Objects section.
public class Rectangle {
private int x, y;
private int width, height;
public Rectangle() {
this(1, 1);
}
public Rectangle(int width, int height) {
this( 0,0,width, height);
}
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
}
This class contains a set of constructors. Each constructor initializes some or all of the rectangle's member variables.
As everybody already have said, you use this(…), which is called an explicit constructor invocation.
However, keep in mind that within such an explicit constructor invocation statement you may not refer to
any instance variables or
any instance methods or
any inner classes declared in this class or any superclass, or
this or
super.
As stated in JLS (§8.8.7.1).
Yes, any number of constructors can be present in a class and they can be called by another constructor using this() [Please do not confuse this() constructor call with this keyword]. this() or this(args) should be the first line in the constructor.
Example:
Class Test {
Test() {
this(10); // calls the constructor with integer args, Test(int a)
}
Test(int a) {
this(10.5); // call the constructor with double arg, Test(double a)
}
Test(double a) {
System.out.println("I am a double arg constructor");
}
}
This is known as constructor overloading.
Please note that for constructor, only overloading concept is applicable and not inheritance or overriding.
Using this keyword we can call one constructor in another constructor within same class.
Example :-
public class Example {
private String name;
public Example() {
this("Mahesh");
}
public Example(String name) {
this.name = name;
}
}
Yes it is possible to call one constructor from another. But there is a rule to it. If a call is made from one constructor to another, then
that new constructor call must be the first statement in the current constructor
public class Product {
private int productId;
private String productName;
private double productPrice;
private String category;
public Product(int id, String name) {
this(id,name,1.0);
}
public Product(int id, String name, double price) {
this(id,name,price,"DEFAULT");
}
public Product(int id,String name,double price, String category){
this.productId=id;
this.productName=name;
this.productPrice=price;
this.category=category;
}
}
So, something like below will not work.
public Product(int id, String name, double price) {
System.out.println("Calling constructor with price");
this(id,name,price,"DEFAULT");
}
Also, in the case of inheritance, when sub-class's object is created, the super class constructor is first called.
public class SuperClass {
public SuperClass() {
System.out.println("Inside super class constructor");
}
}
public class SubClass extends SuperClass {
public SubClass () {
//Even if we do not add, Java adds the call to super class's constructor like
// super();
System.out.println("Inside sub class constructor");
}
}
Thus, in this case also another constructor call is first declared before any other statements.
I will tell you an easy way
There are two types of constructors:
Default constructor
Parameterized constructor
I will explain in one Example
class ConstructorDemo
{
ConstructorDemo()//Default Constructor
{
System.out.println("D.constructor ");
}
ConstructorDemo(int k)//Parameterized constructor
{
this();//-------------(1)
System.out.println("P.Constructor ="+k);
}
public static void main(String[] args)
{
//this(); error because "must be first statement in constructor
new ConstructorDemo();//-------(2)
ConstructorDemo g=new ConstructorDemo(3);---(3)
}
}
In the above example I showed 3 types of calling
this() call to this must be first statement in constructor
This is Name less Object. this automatically calls the default constructor.
3.This calls the Parameterized constructor.
Note:
this must be the first statement in the constructor.
You can a constructor from another constructor of same class by using "this" keyword.
Example -
class This1
{
This1()
{
this("Hello");
System.out.println("Default constructor..");
}
This1(int a)
{
this();
System.out.println("int as arg constructor..");
}
This1(String s)
{
System.out.println("string as arg constructor..");
}
public static void main(String args[])
{
new This1(100);
}
}
Output -
string as arg constructor..
Default constructor..
int as arg constructor..
Calling constructor from another constructor
class MyConstructorDemo extends ConstructorDemo
{
MyConstructorDemo()
{
this("calling another constructor");
}
MyConstructorDemo(String arg)
{
System.out.print("This is passed String by another constructor :"+arg);
}
}
Also you can call parent constructor by using super() call
There are design patterns that cover the need for complex construction - if it can't be done succinctly, create a factory method or a factory class.
With the latest java and the addition of lambdas, it is easy to create a constructor which can accept any initialization code you desire.
class LambdaInitedClass {
public LamdaInitedClass(Consumer<LambdaInitedClass> init) {
init.accept(this);
}
}
Call it with...
new LambdaInitedClass(l -> { // init l any way you want });
Pretty simple
public class SomeClass{
private int number;
private String someString;
public SomeClass(){
number = 0;
someString = new String();
}
public SomeClass(int number){
this(); //set the class to 0
this.setNumber(number);
}
public SomeClass(int number, String someString){
this(number); //call public SomeClass( int number )
this.setString(someString);
}
public void setNumber(int number){
this.number = number;
}
public void setString(String someString){
this.someString = someString;
}
//.... add some accessors
}
now here is some small extra credit:
public SomeOtherClass extends SomeClass {
public SomeOtherClass(int number, String someString){
super(number, someString); //calls public SomeClass(int number, String someString)
}
//.... Some other code.
}
Hope this helps.
Yes it is possible to call one constructor from another with use of this()
class Example{
private int a = 1;
Example(){
this(5); //here another constructor called based on constructor argument
System.out.println("number a is "+a);
}
Example(int b){
System.out.println("number b is "+b);
}
You can call another constructor via the this(...) keyword (when you need to call a constructor from the same class) or the super(...) keyword
(when you need to call a constructor from a superclass).
However, such a call must be the first statement of your constructor. To overcome this limitation, use this answer.
The keyword this can be used to call a constructor from a constructor, when writing several constructor for a class, there are times when you'd like to call one constructor from another to avoid duplicate code.
Bellow is a link that I explain other topic about constructor and getters() and setters() and I used a class with two constructors. I hope the explanations and examples help you.
Setter methods or constructors
I know there are so many examples of this question but what I found I am putting here to share my Idea. there are two ways to chain constructor. In Same class you can use this keyword. in Inheritance, you need to use super keyword.
import java.util.*;
import java.lang.*;
class Test
{
public static void main(String args[])
{
Dog d = new Dog(); // Both Calling Same Constructor of Parent Class i.e. 0 args Constructor.
Dog cs = new Dog("Bite"); // Both Calling Same Constructor of Parent Class i.e. 0 args Constructor.
// You need to Explicitly tell the java compiler to use Argument constructor so you need to use "super" key word
System.out.println("------------------------------");
Cat c = new Cat();
Cat caty = new Cat("10");
System.out.println("------------------------------");
// Self s = new Self();
Self ss = new Self("self");
}
}
class Animal
{
String i;
public Animal()
{
i = "10";
System.out.println("Animal Constructor :" +i);
}
public Animal(String h)
{
i = "20";
System.out.println("Animal Constructor Habit :"+ i);
}
}
class Dog extends Animal
{
public Dog()
{
System.out.println("Dog Constructor");
}
public Dog(String h)
{
System.out.println("Dog Constructor with habit");
}
}
class Cat extends Animal
{
public Cat()
{
System.out.println("Cat Constructor");
}
public Cat(String i)
{
super(i); // Calling Super Class Paremetrize Constructor.
System.out.println("Cat Constructor with habit");
}
}
class Self
{
public Self()
{
System.out.println("Self Constructor");
}
public Self(String h)
{
this(); // Explicitly calling 0 args constructor.
System.out.println("Slef Constructor with value");
}
}
It is called Telescoping Constructor anti-pattern or constructor chaining. Yes, you can definitely do. I see many examples above and I want to add by saying that if you know that you need only two or three constructor, it might be ok. But if you need more, please try to use different design pattern like Builder pattern. As for example:
public Omar(){};
public Omar(a){};
public Omar(a,b){};
public Omar(a,b,c){};
public Omar(a,b,c,d){};
...
You may need more. Builder pattern would be a great solution in this case. Here is an article, it might be helpful
https://medium.com/#modestofiguereo/design-patterns-2-the-builder-pattern-and-the-telescoping-constructor-anti-pattern-60a33de7522e
Yes, you can call constructors from another constructor. For example:
public class Animal {
private int animalType;
public Animal() {
this(1); //here this(1) internally make call to Animal(1);
}
public Animal(int animalType) {
this.animalType = animalType;
}
}
you can also read in details from
Constructor Chaining in Java
Originally from an anser by Mirko Klemm, slightly modified to address the question:
Just for completeness: There is also the Instance initialization block that gets executed always and before any other constructor is called. It consists simply of a block of statements "{ ... }" somewhere in the body of your class definition. You can even have more than one. You can't call them, but they're like "shared constructor" code if you want to reuse some code across constructors, similar to calling methods.
So in your case
{
System.out.println("this is shared constructor code executed before the constructor");
field1 = 3;
}
There is also a "static" version of this to initialize static members: "static { ... }"
I prefer this way:
class User {
private long id;
private String username;
private int imageRes;
public User() {
init(defaultID,defaultUsername,defaultRes);
}
public User(String username) {
init(defaultID,username, defaultRes());
}
public User(String username, int imageRes) {
init(defaultID,username, imageRes);
}
public User(long id, String username, int imageRes) {
init(id,username, imageRes);
}
private void init(long id, String username, int imageRes) {
this.id=id;
this.username = username;
this.imageRes = imageRes;
}
}
I am trying to get the print method in my actor class to print the String that was
built in the toString() method. However I keep getting an error. (invalid method declaration, return type required)
public class actor {
private String name;
private String address;
private int age;
public actor(String name, String address, int age) {
this.name = name;
this.address = address;
this.age = age;
}
public void setName (String name) {
this.name = name;
}
public void setAddress (String address) {
this.address = address;
}
public void setAge (int age) {
this.age = age;
}
public void setFilm () {
}
public String getName () {
return name;
}
public String getAddress () {
return address;
}
public String toString (String name, int age, String address){
return name+" who's "+age+" and lives in "+address;
}
public void print (){
String a = toString();
System.out.println(a);
}
print();
}
I have been trying to get this working for quite a while to no avail.
Here's the two parts to the trouble you're having:
In order to run your program, you have to have a main method.
You have to understand what static and non-static mean.
First, as mentioned by others, you can't just have a method run because it's declared and defined in your class. You actually need to have it called, directly or indirectly, by the main method. The main method is written like this:
public static void main(String[] args) {
// Do Stuff
}
Secondly, you have to understand what static and non-static mean. Which means, you have to understand the difference between classes and objects.
Classes are blue prints. They describe how to build a particular type of object, what properties (or fields) it has, and what methods can be called off of it.
Objects are the actual instances of objects declared by a class. Think of it like this: A class is like the blueprint for a smart car. The objects are the smart cars themselves.
So now, static vs non-static.
Static means that it belongs to the class (the blueprint), rather than to the actual object. The main method, you will notice, is static. It belongs to the class it's declared in, rather than to any instance objects. This means, outside of itself, the main method knows only about the class that it's in, and any other static methods or objects in that class. Things that are not static belong to the actual objects created from the class -- and the main method will know nothing about these actual objects, unless they are created inside of the main method itself.
So, something like this won't work:
public class StuffDoer {
public void doStuff {
System.out.println("Doing Stuff");
}
public static void main(String[] args) {
doStuff(); // Won't work!
// You can't call a non-static, instance method in a static method!
}
}
Instead, you can first create a new instance object of your class inside of the main method, and then call the non-static instance method off of your instance object:
public class StuffDoer {
public void doStuff {
System.out.println("Doing Stuff");
}
public static void main(String[] args) {
new StuffDoer().doStuff(); // This will work,
// because now you have an instance to call the instance method off of.
}
}
This is usually not as good of a choice, but will also work:
public class StuffDoer {
public static void doStuff { //Now, we make this method static
System.out.println("Doing Stuff");
}
public static void main(String[] args) {
doStuff(); // This will work now, because this method is static.
}
}
You're trying to call print() from your class body. Instead, write a main method and print from there:
public static void main(String[] args) {
Actor a = new Actor(...);
a.print();
}
You should have a main function to let the program run, like:
remove the last line print() then create a new file call Main.java, write
package yourPackage // put them into the same package,
main class can call actor class
public class Main{
public static void main(String[] args) {
actor a = new actor();
a.print();
}
}
Why do you need print() method ? You can just use -
Actor a = new Actor(...);
System.out.println(a);
This will implicitly execute toString() method
Ideally you should do this way. Since purpose of toString() method is to give meaningful String representation of an object.
actor actorObj = new actor();
System.out.println(actorObj );
Calling print(); on class body is invalid. Remove following method call.
print();
First off, you should be calling the print() method from somewhere else (main for example). Even with that, you have an error: You are calling the toString() method (with no arguments, which is taken from the Object class). Just remove the arguments from your toString method to override that one. It can see the fields of its own class anyways. With this, you can do something like the following, and take advantage of Java's default toString call:
public static void main(String[] args) {
System.out.println(new Actor("Bob", "410 Main Street", 42);
}
Java does not allow you to call a method in the body of a class as you are attempting to do with the line of code that is print(); You must put the call to print inside another method. For example
public static void main(String[] args) {
actor a = new actor();
a.print();
}
By adding a main method to your class and using the constructor for Actor in that method you create an Author object. On this Author object call print().
TJamesBoone has given a really good answer to give you an understanding of what is really happening. Follow his answer and it will do as you want.
https://stackoverflow.com/a/19981973/1785341
here is your code.. compile and run..
public class actor {
private String name;
private String address;
private int age;
public actor(String name, String address, int age) {
this.name = name;
this.address = address;
this.age = age;
}
public void setName (String name) {
this.name = name;
}
public void setAddress (String address) {
this.address = address;
}
public void setAge (int age) {
this.age = age;
}
public void setFilm () {
}
public String getName () {
return name;
}
public String getAddress () {
return address;
}
#Override
public String toString (){
return name+" who's "+age+" and lives in "+address;
}
public void print (){
//String a = toString();
System.out.println(this);
}
public static void main( String[] args )
{
actor a = new actor( "xyz","abc",20 );
a.print();
}
}
Simple as it is....
Once you write toString() method in a class then do another method called print() and call inside the print() method toString() method.
public void print()
{
System.out.println(toString());
}
class Dad
{
protected static String me = "dad";
public void printMe()
{
System.out.println(me);
}
}
class Son extends Dad
{
protected static String me = "son";
}
public void doIt()
{
new Son().printMe();
}
The function doIt will print "dad". Is there a way to make it print "son"?
In short, no, there is no way to override a class variable.
You do not override class variables in Java you hide them. Overriding is for instance methods. Hiding is different from overriding.
In the example you've given, by declaring the class variable with the name 'me' in class Son you hide the class variable it would have inherited from its superclass Dad with the same name 'me'. Hiding a variable in this way does not affect the value of the class variable 'me' in the superclass Dad.
For the second part of your question, of how to make it print "son", I'd set the value via the constructor. Although the code below departs from your original question quite a lot, I would write it something like this;
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public void printName() {
System.out.println(name);
}
}
The JLS gives a lot more detail on hiding in section 8.3 - Field Declarations
Yes. But as the variable is concerned it is overwrite (Giving new value to variable. Giving new definition to the function is Override). Just don't declare the variable but initialize (change) in the constructor or static block.
The value will get reflected when using in the blocks of parent class
if the variable is static then change the value during initialization itself with static block,
class Son extends Dad {
static {
me = "son";
}
}
or else change in constructor.
You can also change the value later in any blocks. It will get reflected in super class
Yes, just override the printMe() method:
class Son extends Dad {
public static final String me = "son";
#Override
public void printMe() {
System.out.println(me);
}
}
You can create a getter and then override that getter. It's particularly useful if the variable you are overriding is a sub-class of itself. Imagine your super class has an Object member but in your sub-class this is now more defined to be an Integer.
class Dad
{
private static final String me = "dad";
protected String getMe() {
return me;
}
public void printMe()
{
System.out.println(getMe());
}
}
class Son extends Dad
{
private static final String me = "son";
#Override
protected String getMe() {
return me;
}
}
public void doIt()
{
new Son().printMe(); //Prints "son"
}
If you are going to override it I don't see a valid reason to keep this static. I would suggest the use of abstraction (see example code). :
public interface Person {
public abstract String getName();
//this will be different for each person, so no need to make it concrete
public abstract void setName(String name);
}
Now we can add the Dad:
public class Dad implements Person {
private String name;
public Dad(String name) {
setName(name);
}
#Override
public final String getName() {
return name;
}
#Override
public final void setName(String name) {
this.name = name;
}
}
the son:
public class Son implements Person {
private String name;
public Son(String name) {
setName(name);
}
#Override
public final String getName() {
return name;
}
#Override
public final void setName(String name) {
this.name = name;
}
}
and Dad met a nice lady:
public class StepMom implements Person {
private String name;
public StepMom(String name) {
setName(name);
}
#Override
public final String getName() {
return name;
}
#Override
public final void setName(String name) {
this.name = name;
}
}
Looks like we have a family, lets tell the world their names:
public class ConsoleGUI {
public static void main(String[] args) {
List<Person> family = new ArrayList<Person>();
family.add(new Son("Tommy"));
family.add(new StepMom("Nancy"));
family.add(new Dad("Dad"));
for (Person person : family) {
//using the getName vs printName lets the caller, in this case the
//ConsoleGUI determine versus being forced to output through the console.
System.out.print(person.getName() + " ");
System.err.print(person.getName() + " ");
JOptionPane.showMessageDialog(null, person.getName());
}
}
}
System.out Output : Tommy Nancy Dad
System.err is the same as above(just has red font)
JOption Output: Tommy then Nancy then Dad
This looks like a design flaw.
Remove the static keyword and set the variable for example in the constructor. This way Son just sets the variable to a different value in his constructor.
Though it is true that class variables may only be hidden in subclasses, and not overridden, it is still possible to do what you want without overriding printMe () in subclasses, and reflection is your friend. In the code below I omit exception handling for clarity. Please note that declaring me as protected does not seem to have much sense in this context, as it is going to be hidden in subclasses...
class Dad
{
static String me = "dad";
public void printMe ()
{
java.lang.reflect.Field field = this.getClass ().getDeclaredField ("me");
System.out.println (field.get (null));
}
}
https://docs.oracle.com/javase/tutorial/java/IandI/hidevariables.html
It's called Hiding Fields
From the link above
Within a class, a field that has the same name as a field in the superclass hides the superclass's field, even if their types are different. Within the subclass, the field in the superclass cannot be referenced by its simple name. Instead, the field must be accessed through super, which is covered in the next section. Generally speaking, we don't recommend hiding fields as it makes code difficult to read.
class Dad
{
protected static String me = "dad";
public void printMe()
{
System.out.println(me);
}
}
class Son extends Dad
{
protected static String _me = me = "son";
}
public void doIt()
{
new Son().printMe();
}
... will print "son".
It indeed prints 'dad', since the field is not overridden but hidden. There are three approaches to make it print 'son':
Approach 1: override printMe
class Dad
{
protected static String me = "dad";
public void printMe()
{
System.out.println(me);
}
}
class Son extends Dad
{
protected static String me = "son";
#override
public void printMe()
{
System.out.println(me);
}
}
public void doIt()
{
new Son().printMe();
}
Approach 2: don't hide the field and initialize it in the constructor
class Dad
{
protected static String me = "dad";
public void printMe()
{
System.out.println(me);
}
}
class Son extends Dad
{
public Son()
{
me = "son";
}
}
public void doIt()
{
new Son().printMe();
}
Approach 3: use the static value to initialize a field in the constructor
class Dad
{
private static String meInit = "Dad";
protected String me;
public Dad()
{
me = meInit;
}
public void printMe()
{
System.out.println(me);
}
}
class Son extends Dad
{
private static String meInit = "son";
public Son()
{
me = meInit;
}
}
public void doIt()
{
new Son().printMe();
}
Variables don't take part in overrinding. Only methods do. A method call is resolved at runtime, that is, the decision to call a method is taken at runtime, but the variables are decided at compile time only. Hence that variable is called whose reference is used for calling and not of the runtime object.
Take a look at following snippet:
package com.demo;
class Bike {
int max_speed = 90;
public void disp_speed() {
System.out.println("Inside bike");
}
}
public class Honda_bikes extends Bike {
int max_speed = 150;
public void disp_speed() {
System.out.println("Inside Honda");
}
public static void main(String[] args) {
Honda_bikes obj1 = new Honda_bikes();
Bike obj2 = new Honda_bikes();
Bike obj3 = new Bike();
obj1.disp_speed();
obj2.disp_speed();
obj3.disp_speed();
System.out.println("Max_Speed = " + obj1.max_speed);
System.out.println("Max_Speed = " + obj2.max_speed);
System.out.println("Max_Speed = " + obj3.max_speed);
}
}
When you run the code, console will show:
Inside Honda
Inside Honda
Inside bike
Max_Speed = 150
Max_Speed = 90
Max_Speed = 90
only by overriding printMe():
class Son extends Dad
{
public void printMe()
{
System.out.println("son");
}
}
the reference to me in the Dad.printMe method implicitly points to the static field Dad.me, so one way or another you're changing what printMe does in Son...
You cannot override variables in a class. You can override only methods. You should keep the variables private otherwise you can get a lot of problems.
No. Class variables(Also applicable to instance variables) don't exhibit overriding feature in Java as class variables are invoked on the basis of the type of calling object. Added one more class(Human) in the hierarchy to make it more clear. So now we have
Son extends Dad extends Human
In the below code, we try to iterate over an array of Human, Dad and Son objects, but it prints Human Class’s values in all cases as the type of calling object was Human.
class Human
{
static String me = "human";
public void printMe()
{
System.out.println(me);
}
}
class Dad extends Human
{
static String me = "dad";
}
class Son extends Dad
{
static String me = "son";
}
public class ClassVariables {
public static void main(String[] abc) {
Human[] humans = new Human[3];
humans[0] = new Human();
humans[1] = new Dad();
humans[2] = new Son();
for(Human human: humans) {
System.out.println(human.me); // prints human for all objects
}
}
}
Will print
human
human
human
So no overriding of Class variables.
If we want to access the class variable of actual object from a reference variable of its parent class, we need to explicitly tell this to compiler by casting parent reference (Human object) to its type.
System.out.println(((Dad)humans[1]).me); // prints dad
System.out.println(((Son)humans[2]).me); // prints son
Will print
dad
son
On how part of this question:- As already suggested override the printMe() method in Son class, then on calling
Son().printMe();
Dad's Class variable "me" will be hidden because the nearest declaration(from Son class printme() method) of the "me"(in Son class) will get the precedence.
Just Call super.variable in sub class constructor
public abstract class Beverage {
int cost;
int getCost() {
return cost;
}
}`
public class Coffee extends Beverage {
int cost = 10;
Coffee(){
super.cost = cost;
}
}`
public class Driver {
public static void main(String[] args) {
Beverage coffee = new Coffee();
System.out.println(coffee.getCost());
}
}
Output is 10.
Of course using private attributes, and getters and setters would be the recommended thing to do, but I tested the following, and it works... See the comment in the code
class Dad
{
protected static String me = "dad";
public void printMe()
{
System.out.println(me);
}
}
class Son extends Dad
{
protected static String me = "son";
/*
Adding Method printMe() to this class, outputs son
even though Attribute me from class Dad can apparently not be overridden
*/
public void printMe()
{
System.out.println(me);
}
}
class Tester
{
public static void main(String[] arg)
{
new Son().printMe();
}
}
Sooo ... did I just redefine the rules of inheritance or did I put Oracle into a tricky situation ?
To me, protected static String me is clearly overridden, as you can see when you execute this program. Also, it does not make any sense to me why attributes should not be overridable.
Why would you want to override variables when you could easily reassign them in the subClasses.
I follow this pattern to work around the language design. Assume a case where you have a weighty service class in your framework which needs be used in different flavours in multiple derived applications.In that case , the best way to configure the super class logic is by reassigning its 'defining' variables.
public interface ExtensibleService{
void init();
}
public class WeightyLogicService implements ExtensibleService{
private String directoryPath="c:\hello";
public void doLogic(){
//never forget to call init() before invocation or build safeguards
init();
//some logic goes here
}
public void init(){}
}
public class WeightyLogicService_myAdaptation extends WeightyLogicService {
#Override
public void init(){
directoryPath="c:\my_hello";
}
}