[Go to site: main page, start]

0% found this document useful (0 votes)
10 views9 pages

Java

The document provides an overview of methods in Java, including their declaration, parameters, return types, and the distinction between static and instance methods. It also covers method overloading, overriding, and the principles of inheritance, emphasizing the access to inherited members and the use of constructors. Best practices for method naming, structure, and common mistakes are highlighted to aid in effective Java programming.

Uploaded by

aistories791
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views9 pages

Java

The document provides an overview of methods in Java, including their declaration, parameters, return types, and the distinction between static and instance methods. It also covers method overloading, overriding, and the principles of inheritance, emphasizing the access to inherited members and the use of constructors. Best practices for method naming, structure, and common mistakes are highlighted to aid in effective Java programming.

Uploaded by

aistories791
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Methods in Java

A method in Java is a block of code that performs a specific task. It belongs to a class and defines the
behavior of objects. Methods let us reuse code and keep programs organized. To declare a method, you
write a method signature (its name and parameters) plus the method body. The only required parts are the
return type, the method name, parentheses, and a body in braces. For example, public int add(int
a, int b) { … } declares a method named add that takes two integers and returns an integer.

● Modifiers: (e.g. public, private, static) specify access and behavior.


● Return type: the data type the method returns, or void if it returns nothing.
● Method name: usually a verb in lowerCamelCase (e.g. getResult or calculateSum).
● Parameters: zero or more input variables inside (), separated by commas. For example, in
void greet(String name), name is a parameter.
● Body: the code between {} that runs when the method is called.

Together, a method’s signature is its name plus its parameter types. The signature (and class) must
uniquely identify the method. For instance, calculate(int) and calculate(double) are
different signatures. By convention, method names should start with a verb, e.g. run, getBackground,
setX.

java
public class Example {
// A simple method that prints a message
public void sayHello() {
[Link]("Hello, World!");
}

public static void main(String[] args) {


Example obj = new Example(); // create an object of Example
[Link](); // call the method
}
}

Parameters and Arguments


Methods can take inputs known as parameters. Parameters act like variables inside the method. When
you call a method, you provide arguments that fill those parameters. For example, in:

java
static void showName(String name) {
[Link](name + " Refsnes");
}

public static void main(String[] args) {


showName("Liam"); // "Liam" is the argument passed
showName("Jenny");
}

Here name is a parameter, and "Liam" or "Jenny" are arguments passed to it. You can define multiple
parameters by separating them with commas. Important: when calling a method with multiple
parameters, the number and order of arguments must match the parameters.

Example – multiple parameters:


java
static void showInfo(String name, int age) {
[Link](name + " is " + age);
}
public static void main(String[] args) {
showInfo("Liam", 5); // OK: "Liam" → name, 5 → age
showInfo("Jenny", 8);
}


● If a method takes no parameters, use empty parentheses: e.g. void printDate() { … }.

Return Types
A method may return a value. Its return type is the type of that value. If a method does not return
anything, its return type must be void. If the return type is not void, the method must use the return
keyword to return a value of the correct type. For example:

java
class MathExample {
double average(double x, double y) {
double result = (x + y) / 2.0;
return result; // return the double value
}
public static void main(String[] args) {
MathExample ex = new MathExample();
[Link]([Link](5.5, 6.5)); // prints 6.0
}
}

In the average method above, the return type is double, and we use return res; to send back a
double. If a method’s return type is void, you do not need a return statement (though you can use
return; to exit early).

Key points about return types:

● A method with a non-void return type must return a value of that type before it ends.
● A void method does not return a value. You can omit return, or use return; to stop
execution.
● You cannot have two methods with the same signature that only differ by return type; the
signature (name + parameters) must be unique.

Static vs Instance Methods


Methods declared with the static keyword belong to the class, not to any particular object. You can call
a static method using the class name without creating an object. In contrast, instance methods
(non-static) belong to objects and must be called on an instance.

● Static method: Belongs to the class itself. Can be called without an object. Static methods cannot
use instance variables or this.
● Instance method: Belongs to an object. Requires creating an object of the class and calling the
method on it. Instance methods can access the current object via this.

For example, [Link]() is a static method (you don’t do new Math().random()). In your
classes:

java
class Greeter {
// static method: called via class name
public static void greet() {
[Link]("Hello!");
}
// instance method: needs an object
public void sayHi() {
[Link]("Hi there!");
}
public static void main(String[] args) {
[Link](); // static call – no object needed【32†L132-L135】

Greeter g = new Greeter();


[Link](); // instance call – using object g【32†L176-L178】
}
}

In the code above, greet() is static and is called as [Link](). The sayHi() method is
instance-level, so we first create Greeter g = new Greeter(); then call [Link](). A
common mistake is trying to use instance variables or methods directly inside a static method (like main)
without an object.

Method Signature and Overloading


A method’s signature is its name plus its parameter types. Java allows method overloading, where
multiple methods in the same class have the same name but different parameter lists. The differences can
be in the number or types of parameters (or their order). Overloaded methods act like different methods.
For example:
java
class Calculator {
int sum(int a, int b) {
return a + b;
}
int sum(int a, int b, int c) {
return a + b + c;
}
double sum(double x, double y) {
return x + y;
}
public static void main(String[] args) {
Calculator c = new Calculator();
[Link]([Link](3, 4)); // calls sum(int,int) -> 7
[Link]([Link](3, 4, 5)); // calls sum(int,int,int) -> 12
[Link]([Link](2.5, 4.0)); // calls sum(double,double) -> 6.5
}
}

Here we have three methods all named sum but with different parameter lists. Java picks the correct one
based on the arguments we pass. Important: You cannot overload methods by return type alone – the
parameter lists must differ. Also, overloading only applies within the same class (or inherited ones) and is
resolved at compile time. In general, avoid creating too many overloaded methods, as it can make code
harder to read.

Method Overriding
Overriding happens when a subclass (child class) provides its own implementation of a method that is
already defined in its superclass (parent class). The overriding method must have the same name,
parameters, and return type (or a subtype return) as the parent’s method. This allows a subclass to
modify or extend the behavior it inherits. When you call the method on a subclass object, the overridden
version is used (this is called runtime polymorphism). For example:

java
class Animal {
void move() {
[Link]("Animal is moving.");
}
}
class Dog extends Animal {
@Override
void move() { // overriding Animal’s move()
[Link]("Dog is running.");
}
void bark() {
[Link]("Dog is barking.");
}
}
public class Test {
public static void main(String[] args) {
Animal myAnimal = new Dog(); // a Dog object referenced as Animal
[Link](); // calls Dog’s overridden move() -> "Dog is running."
}
}

In this example, Dog overrides the move() method of Animal. Even though myAnimal is of type
Animal, calling [Link]() runs the Dog version at runtime. (Tip: use the @Override
annotation when overriding; if you accidentally mistype the method name or signature, the compiler will
catch it.) Note that static methods cannot be overridden – if a subclass defines a static method with the
same signature, it hides the superclass method instead. Similarly, private methods are not visible to
subclasses and thus cannot be overridden.

Best Practices and Common Mistakes


● Use clear names: Method names should clearly describe what they do and follow
lowerCamelCase. For example, calculateTotal() is better than calc(). Good names act
as documentation.
● Keep methods short: Aim for roughly 10–20 lines per method. If a method grows longer,
consider breaking it into smaller helper methods. This improves readability and maintainability.
● Minimize parameters: Too many parameters can make methods hard to use. If you find a
method needs many inputs, think about grouping related data into objects or splitting the task.
● Proper use of static: Only make a method static if it doesn’t depend on instance data.
Remember you must create an object to call non-static methods (one common error is trying to
use instance variables directly in static methods).
● Match signatures for overriding: When overriding, ensure the subclass method’s signature
(name, parameter types, and return type) exactly matches the parent’s (except that covariant return
types are allowed). A typo or wrong signature creates a new method instead of overriding. Using
@Override helps catch this.
● Return statements: Don’t forget to use return when the method declares a non-void return
type; otherwise the code won’t compile. Also avoid putting code after a return (unreachable
code errors).
● Overloading rules: You cannot overload two methods with the same parameter list even if they
have different return types. The compiler matches methods by name and parameter list only.
● Avoid shadowing mistakes: When a subclass declares a static method with the same signature as
in its superclass, it’s not overriding but hiding the method (which can be confusing). Use
@Override and be careful with static vs instance methods.

Inheritance (Superclass and Subclass)


Inheritance is a core concept in Java that lets one class (the subclass or child) derive from another class
(the superclass or parent). Inheritance promotes code reuse: you can create a new class from an existing
one, automatically acquiring its fields and methods. Except for Object (which has no parent), every
class in Java has exactly one direct superclass (single inheritance). A subclass inherits all public and
protected members from its superclass (and package-private members if they are in the same package),
but private members are not inherited. In effect, a subclass automatically has the behavior of its parent,
and can extend or modify it.

For example, consider class Animal and a subclass class Dog extends Animal { ... }.
Here, Animal is the superclass and Dog is the subclass (child). Because of inheritance, Dog has all the
(non-private) fields and methods of Animal. If Animal had a method public void eat(), then
Dog can call eat() as if it were its own method. You use the extends keyword to declare a subclass:

java
class Animal {
public void eat() {
[Link]("Animal eats");
}
}

class Dog extends Animal {


// Dog inherits eat(), and can add its own members
public void bark() {
[Link]("Dog barks");
}
}

public class Test {


public static void main(String[] args) {
Dog myDog = new Dog();
[Link](); // inherited from Animal
[Link](); // defined in Dog
}
}

In this code, Dog inherits the eat() method from Animal. It adds a new method bark(). You can
use Dog objects anywhere an Animal is expected (because “Dog is-an Animal”).

Access to Inherited Members


Because a subclass inherits its parent’s members, it can use inherited fields and methods directly, just
as if they were declared in the subclass. However:

● Public and protected members of the superclass are inherited (accessible to the subclass). For
example, if Vehicle has a protected String brand field, a subclass Car extends
Vehicle can access brand.
● Default (package-private) members are inherited only if the subclass is in the same package as
the superclass.
● Private members of the superclass are not inherited. (The subclass cannot access private fields or
methods of its parent.) For example, if Vehicle had private int speed, Car cannot see
speed directly. A common fix is to declare fields as protected or provide getter/setter
methods.
You can override inherited methods by declaring a method in the subclass with the same signature. In that
case, the subclass’s version is used (method overriding). If you still want to use the superclass’s original
method, you can call it via [Link](). Fields can also be shadowed (redeclared with the
same name) in a subclass, but this hides the parent field (not usually recommended). Likewise, a subclass
can hide a static method of its parent by declaring a static method with the same signature (this is method
hiding, not overriding).

Example – Access and Overriding: In the Vehicle/Car example below, Car inherits brand and
honk() from Vehicle. We marked brand as protected so Car can see it. Car can also override
or add methods if needed.

java
class Vehicle {
protected String brand = "Ford"; // accessible in subclass (protected)
public void honk() {
[Link]("Tuut, tuut!");
}
}

class Car extends Vehicle {


private String modelName = "Mustang";
public static void main(String[] args) {
Car myCar = new Car();
[Link](); // inherited method, prints "Tuut, tuut!"
[Link]([Link] + " " + [Link]);
// uses inherited field 'brand'
}
}

In this example, Car successfully accesses brand (because it’s protected). If brand had been
declared private in Vehicle, Car could not use it.

Constructors and the super Keyword


Constructors are not inherited by subclasses. However, the first thing a subclass constructor must do is
call one of its superclass’s constructors. You do this using super(...). The call to super (if used)
must be the very first statement in the subclass constructor. For example, given:

java
class Bicycle {
public Bicycle(int startGear) {
// initialize Bicycle
}
}
class MountainBike extends Bicycle {
public int seatHeight;
public MountainBike(int startHeight, int startGear) {
super(startGear); // calls Bicycle(int)
seatHeight = startHeight;
}
}

Here, MountainBike’s constructor calls super(startGear); to invoke the Bicycle constructor.


If you omit the call to super(...), Java will automatically insert a call to the superclass’s
no-argument constructor (i.e. super()). If the superclass does not have a no-arg constructor, you must
explicitly call one of its constructors, or else you will get a compile-time error.

Constructor chaining happens through the inheritance chain: each constructor calls its parent constructor
until eventually reaching Object. Keep in mind:

● Always call super(...) first: If you need to call a superclass constructor with arguments, do
it as the first line.
● If you don’t call it explicitly, Java inserts super() automatically.
● If the superclass lacks a default (no-arg) constructor, forgetting to call super(...) causes an
error.

A typical pattern is:

java
class Parent {
public Parent(int value) { ... }
}
class Child extends Parent {
public Child(int x) {
super(x); // must be first
// child-specific initialization
}
}

If Parent had a no-arg constructor, you could skip super(x), but explicitly calling super(x) is
clearer.

Method Overriding and super


A subclass can override a parent method by providing a new implementation with the same signature.
Use the @Override annotation to catch any mistakes (it ensures your method matches a parent method).
For instance:

java
class Animal {
void speak() {
[Link]("Animal sound");
}
}
class Dog extends Animal {
@Override
void speak() {
[Link](); // optional: call parent method
[Link]("Dog barks");
}
}

In Dog, the speak() method overrides Animal’s speak(). Inside it, we called [Link]() to
invoke the parent’s version (printing "Animal sound"), then added "Dog barks". Calling new
Dog().speak() would output:

nginx
Animal sound
Dog barks

Remember that static methods cannot be overridden; if a subclass declares a static method with the
same signature as one in its superclass, the parent’s method is hidden, not overridden. Also, a subclass
cannot override final methods, and cannot extend a final class.

Best Practices and Common Mistakes


● Use inheritance for “is-a” relationships: Only subclass when the new class truly is a type of the
old class (e.g. Car extends Vehicle). Inappropriate use of inheritance (just for code reuse)
can make code hard to understand.
● protected vs private: Be careful with access modifiers. A subclass cannot access private
members of its parent. Use protected or public getters/setters if the subclass needs access.
● Call super(...) properly: In a subclass constructor, always put the super() call first.
Forgetting this or placing statements before it causes compile errors.
● Match method signatures: When overriding a method, make sure the method signature exactly
matches the parent’s (parameters and return type). A mismatched signature means you’re creating
a new method, not overriding. The @Override annotation is helpful to catch mistakes.
● Single inheritance: Java does not allow a class to extend more than one class (no multiple
inheritance of classes). (You can implement multiple interfaces instead if needed.)
● final keyword: A class declared final cannot be subclassed. Trying to do so is a compile
error.
● Constructor confusion: Parent constructors are not inherited. If the parent has only
parameterized constructors, the child must explicitly call one using super(args).
● Polymorphic casting: You can assign a subclass instance to a superclass reference (upcasting)
safely. But downcasting (superclass to subclass) requires an explicit cast and typically an
instanceof check to avoid errors. For example, an Object obj = new
MountainBike(); is valid, but MountainBike mb = (MountainBike)obj; needs
the cast and only works at runtime if obj really refers to a MountainBike.

You might also like