Altering Parent Method Behavior By Overriding Method It Calls
Apr 21, 2014
I have two classes (Daughter and Son) that contain some very similar method definitions:
public class Family {
public static void main(String[] args) {
Daughter d = new Daughter();
Son s = new Son();
d.speak();
s.speak();
[Code] .....
Each of those classes has a "speak" method with two out of three lines being identical. I could move those into a parent class, but I need each of the child classes to continue to exhibit its unique behavior. I'm trying the approach below, which replaces the unique code with a call to a "placeholder" method that must be implemented by each child class:
public class Family {
public static void main(String[] args) {
Daughter d = new Daughter();
Son s = new Son();
[Code] .....
This works and moves the shared code from two places (the Daughter and Son classes) into one place (the new Mother class, which is now a parent class of Daughter and Son). Something about this feels a bit odd to me, though. It's one thing for a child class to override a parent class's methods to extend or alter their behavior. But, here, I've implemented an abstract method in the parent class to alter what happens when the parent class's method (speak(), in this case) is called, without overriding that parent class method itself.
class One { public static void doStuff() { System.out.println("One"); } }
class Two extends One
[code]....
My understanding of static says that static methods cannot be overrriden but the compilation of the above code results in Overriding rule violation error.
For a few days I've been reading about the importance of overriding the equals method. How overriding it actually determines or checks the values stored in the variable. I realize that you can check the values stored in the primitive datatypes with "==", and when you don't override the equals method it acts the same way, right? When used with a reference datatype, "==" or the default equals() method only compares, or sees, if the variable is pointing to the same instance of a class. For some reason, in the examples, what is taking place to actually check the values stored inside the variables.
Here is part of an example (I've added comments for things that are confusing me):
@Override public boolean equals(Object obj) { //So we use Object here instead of the class type // we're overriding this equals method for? Is this so that we can use it to check different types? (overloading?) if (obj == this) { return true;
//Isn't this checking to see if the calling object is the same as the object we're passing to it? Why doesn't this return false? } if (obj == null || obj.getClass() != this.getClass()) { return false; }
//How exactly do we check the values stored in each object though? }
I am attempting to override the equals method from the Object class which checks if two variables point towards the same object. I want the method to check if if the argument being passed in(an object) has the same data(instance variables) as the object that's calling this method. A NullPointerException is being thrown; Here is the code.
Exception in thread "main" java.lang.NullPointerException at javaapplication5.Product.equals(Product.java:42) at javaapplication5.Product.main(Product.java:24) Java Result: 1
How do i print override the toString for WebBrowser as i would like to print out the object bc. Tested the program and it is fine if i put it in the main method rather than the WebBrowser constructor.
import java.util.*; class ListNode <E> { /* data attributes */ private E element; private ListNode <E> next; /* constructors */ public ListNode(E item) { this(item, null);
If i have 2 classes, Top and ClassB which extends Top
public class Top { String variable; public Top(){ setVariable(); } void setVariable(){ variable = "variable is initialized in Main Class";
[code]....
So what is happening when ClassB inherits from Top?I know that the B constructor is calling super, so does that mean its calling setVariable (in Top?) but as its overridden in ClassB, then that is whats being called and setting the String variable?
I have been working on a simple problem, but I am stuck. I am trying to learn parent and child classes and how they work. The program in broken into three classes; the DemoBook class that runs the various methods, the Book class that gathers information and displays it, and finally a child class of Book (called TextBook) that just gets one piece of data and then is suppossed to return that data back to Book. However, this is not working and I know I am missing something; I believe it has to do with Set and Get methods, but I am confused with how these work.
Java Code:
public class DemoBook { public static void main (String[] args) { Book aBook = new Book(); Textbook aText = new Textbook();
class SubB{ public void foo(){ System.out.println(" x"); } } public class X extends SubB { public void foo() throws RuntimeException{ super.foo(); if(true) throw new RuntimeException(); System.out.println(" B"); } public static void main(String [] args){ new X().foo(); } }
Why the foo method of class X is not throwing a compile error because according to the override rule, if the superclass method has not declared exception, the subclass method can't declare a new exception...
I am trying to calculate a fine in a PoliceOfficer object with method calls to a ParkedCar and ParkingMeter object. The word problem is:
The fine is $25 for the first hour or part of it and $20 for every additional hour of part of it.
My code is:
public class PoliceOfficer public static final int PARKING_FINE1 = 25; public static final int PARKING_FINE2 = 20; public static final int NUMBER_OF_MINUTES_OVER_PARKED = 60; public double calculateFine(){ double calculateFine = 0;
[Code] ....
obviously the fine is not calculated correctly but I'm not sure how to proceed from here...
I think its a standard concept but just not getting it. I have 3 classes:
1) Base class 2) Derived class, which extends base 3) TestClass
public class Base { public void display() { System.out.println("Display method in Base"); } } class Derived extends Base { public void display() { System.out.println("display method in Derived");
[Code] .....
So if i run this, my results are:
Display method in Base display method in Derived display method in Derived
Thats cool, no problems there, but if i change my Display method in Base and Derived to static methods then the results become:
Display method in Base display method in Derived Display method in Base
So why oh why does obj3.display() now print "Display method in Base"?
(and yes I know the calls should be static calls, but for sake of arguments -- or is that the whole problem, that technically obj3.display() is an incorrect call as it can only be Base.display() or Derived.display() when display() is a static method ).
I am trying to use method calls with returns but it keeps on showing errors. The errors say class, interface, or enum expected. I realize this error occurs if there is issue with declaring class - but i can't seem to find the error. I will post the code that shows error.
import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.text.*; public class FuelCost extends JFrame { // declarations Color black = new Color(0, 0, 0);
I have a multithreaded application. I have a Logger class with static methods that I use across threads. Would it behoove me to add the synchronized keyword to the static methods of the Logger class since I use this class statically in different threads?
I want to know is there any way we can call parent class method using child class object without using super keyword in class B in the following program like we can do in c++ by using scoop resolution operator
class A{ public void hello(){ System.out.println("hello"); } } class B extends A{ public void hello(){ //super.hello(); System.out.println("hello1");
I'd like to know how to return a new array, I wrote in a method below the main method. I want to print the array but system.out.print doesn't work for arrays apparently. What structure i should use?
I have to write a method called censor that gets an array of strings from the user as an argument and then returns an array of strings that contains all of the original strings in the same order except those with length of 4. For example if cat, dog, moose, lazy, with was entered, then it would return the exact same thing except for the words with and lazy.
Currently, my code so far just prints [Ljava.lang.String;@38cfdf and im stuck.
import java.util.Scanner; public class censorProgram { public static void main (String args[]){ Scanner input = new Scanner (System.in); System.out.println ("How many words would you like to enter?"); int lineOfText = input.nextInt();
[Code] ....
I have to make new string array in the method and return words without four letters in the main method
Alright, I don't understand how to link my compress method to my return statement method "getPText". Also in my compression I only want it to compress for 3 or more consecutive letters.
I am just trying to test this array, for a locker combination program that involves classes...but the array is printing out the whacky numbers for the location. When I try to call the method in the main, it does not work. How do I call a method that exist within a class into the main method?
public class locker { public static void main(String[] args) { CombinationLock();
I am currently working on a dice game. I have a private method called rollDice and it performs the action of rolling two dice. For my project, I need to create another method called playerRolls and I am supposed to invoke the rollDice method in the playerRolls method and perform actions based off of that. My question right now is how do I invoke a method into another method of the same class?
I need to write a method that will consume string representation of Object type and will return one object of this type. How to set return type for the method in this case?
Here is exmaple :
public <?> identifyType(String typeString){ if (typesString.matches("String")){ return new String(""); }else if (typeString.matches("Integer")){ return new Integer(0); } //....etc..}