[Go to site: main page, start]

0% found this document useful (0 votes)
5 views42 pages

Java Method Types and Constructors Explained

Uploaded by

nayabkcse2125
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)
5 views42 pages

Java Method Types and Constructors Explained

Uploaded by

nayabkcse2125
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- an user defined methods could be classified into following categories-

1. Method with no argument & no return value

2. Method with argument but no return value

3. Method with argument and return value

4. Method with no argument but return value

The Genral form of a Method will be-

access_specifier return_type method_name(argument)

body of the method

Note- For accessing the member of a class you must create the object of that class like the
following-

class objectname=new classname();

[Link]();

1. Method with no argument & no return value- if you want to perform any static operation,
then use such type of method.

ex.

WAP which generates the following output-

**************************************************************************

Sushant T College

**************************************************************************
**************************************************************************

Sol-

class logic

public void Line()

int i;

for(i=1;i<=70;i++)

[Link]("*");

[Link]();

class test

public static void main(String args[])

logic obj=new logic();

[Link]();

[Link]("\t\t\tSushant IT College");

[Link]();

[Link]();
}

______________________________________________________________________________
___

2. Method with argument but no return value- if you want to perform any dynamic operation
according to given value, but the oocurance of result is more than one then you can use such
type of method.

ex.

WAP which generates the following output-

**************************************************************************

Sushant T College

&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Sol-

class logic

public void Line(String ch)

int i;

for(i=1;i<=70;i++)

[Link](ch);

[Link]();
}

class test

public static void main(String args[])

logic obj=new logic();

[Link]("*");

[Link]("\t\t\tSushant IT College");

[Link]("&");

[Link]("^");

Que- Create a Method named as table() which contains a number as argument & print the
table of given number.

_________________________________________________________

3. Method with argument and return value- if you want to perform any dynamic operation
by a given value & result is an aggregate value then you can use such type of methods.

Que- Create a Method named as max() which contains three numbers as argument & return
the largest one.

Sol-1

class logic

public int max(int a,int b,int c)

{
int m;

if(a>b && a>c)

m=a;

else if(b>a &&b>c)

m=b;

else

m=c;

return m;

class test

public static void main(String args[])

logic obj=new logic();

int res=[Link](100,20,4);

[Link]("Largest : "+res);

Que- Create a method named as fact() which contains a number as argument & return the
factorial of that number.

Que- Create a method named as power() which contains base number(x) and power
number(n) as argument & return x to the power n.
_______________________________

4. Method with no argument but return value- Such Kinds of method works on the members
of class-

for ex.

class logic

int a,b,c;

public void get(int x,int y,int z)

a=x;

b=y;

c=z;

public int max()

int m;

if(a>b && a>c)

m=a;

else if(b>a &&b>c)

m=b;

else

m=c;
return m;

public void show()

[Link]("Largest : "+max());

class test

public static void main(String args[])

logic obj=new logic();

[Link](100,20,4);

[Link]();

_______________________________________________________________________

Method Overloading-It is the practical implementation of Polymorphism. If class contains


more than one method with same name but different argument, then this term is known as
method overloading.

Que-Create an overoaded method named as reverse() which reverse() the digits of a number
or characters of a string as per the given argument.
Que- Create an overloaded method named as lcm() which return the lcm of either 2 , 3 or 4
given values.

Sol-2

class logic

int m,i,res;

public int lcm(int a,int b)

m=a*b;

for(i=1;i<=m;i++)

if(i%a==0 && i%b==0)

res=i;

break;

return res;

public int lcm(int a,int b,int c)

m=a*b*c;

for(i=1;i<=m;i++)
{

if(i%a==0 && i%b==0 && i%c==0)

res=i;

break;

return res;

public int lcm(int a,int b,int c,int d)

m=a*b*c*d;

for(i=1;i<=m;i++)

if(i%a==0 && i%b==0 && i%c==0 && i%d==0)

res=i;

break;

return res;

}
class test

public static void main(String args[])

logic obj=new logic();

[Link]("LCM Among Two Values :"+[Link](3,5));

[Link]("LCM Among Three Values :"+[Link](2,4,6));

[Link]("LCM Among Two Values :"+[Link](4,6,8,5));

______________________________________________________________________________
_______

Constructors- They are used for initilizing the members of a class. the propertoes of
constructors will be-

1. The name of constructor must be same as the name of class.

2. They did not return any value not even void.

3. They called automatically when the object of the class is created.

Types of Constructors

1. Default Constructors

2. Parametrized Constructors

3. Overloaded Constructors

1. Default Constructors- If a constructors did not contains any argument then it is known as
default constructors.
eg.

class cons

String name;

int age;

public cons()

name="Bzar";

age=24;

public void show()

[Link]("Name : "+name);

[Link]("Age : "+age);

class test

public static void main(String args[])

cons obj=new cons();

[Link]();

}
___________________________________________________________

2. Parametrized Constructors- The constrctors which takes the arguments are known as
parametrized constructors. the value of argument must be passed at the time of object
creation.

class cons

String name;

int age;

public cons(String n,int a)

name=n;

age=a;

public void show()

[Link]("Name : "+name);

[Link]("Age : "+age);

class test

{
public static void main(String args[])

cons obj=new cons("Quamar",25);

[Link]();

______________________________________________________________________________
__

3. Overloaded Constructors - If a class contains more than one construtor then this term is
known as overloaded constructor.

class Line

int i;

public Line()

for(i=1;i<=70;i++)

[Link]("*");

[Link]();

public Line(String ch)

{
for(i=1;i<=70;i++)

[Link](ch);

[Link]();

class test

public static void main(String args[])

Line obj;

[Link]("First Line Style");

obj=new Line();

[Link]("Second Line Style");

obj=new Line("&");

_________________________________________________________

Inheritance- This is the concept of reusability.

for definiting a sub class you must follow the folliwng syntax-
class subclassname extends superclassname

body of the class

Note - remember only public member of super class inherited in sub class.

Syntax for creating sub class

class subclassname extends superclassname

body of the class

class first

public void one()

[Link]("First Method of The Super Class Class");

privateone();

private void privateone()

[Link]("private Method of The Super Class Class");

}
class sec extends first

public void two()

[Link](" Method of The Sub Class Class");

class test

public static void main(String args[])

sec obj=new sec();

[Link]();

[Link]();

________________________________________

using this keyword- We can use two variations of this keyword, these are-

1. this statement

2. this() method

1. this statement- It reference the member of same class.


class thdemo

int a,b;

public void get(int a,int b)

this.a=a;

this.b=b;

public void put()

[Link]("First Value : "+a);

[Link]("Second Value : "+b);

class test

public static void main(String args[])

thdemo obj=new thdemo();

[Link](10,20);

[Link]();

}
}

____________________________________________________

this () method- It is used for calling the constructor of class inside the another constructor of
same class.

class thdemo

public thdemo()

[Link]("First Constructor");

public thdemo(int n)

this();

[Link]("Second Constructor");

class test

public static void main(String args[])

thdemo obj=new thdemo(10);

}
}

___________________________________________________________________________

using super keyword- like this we can also use two variations of super keyword-

1. super statement

2. super method

1. super statement - this statement is used for accessing the member of super class inside sub
class.

class first

int a,b;

public void get(int a,int b)

this.a=a;

this.b=b;

class sec extends first

int a,b;

public void set()

this.a=super.a;

this.b=super.b;
}

public void show()

[Link]("First Value : "+a);

[Link]("Second Value : "+b);

class test

public static void main(String args[])

sec obj=new sec();

[Link](10,20);

[Link]();

[Link]();

________________________________

2. super() method- It is used for calling the constructor of super class inside the sub class.

class first

{
public first()

[Link]("First Constructor");

public first(int n)

[Link]("Second Constructor");

class sec extends first

public sec()

super(10);

[Link]("Constructor of Sub Class");

class test

public static void main(String args[])

sec obj=new sec();


}

_______________________________________________________________

static keyword- we use 3 variations of static keyword, These are-

1. static variable

2. static methods

3. static class

1. static variable- The are known as class level variables & they share a single copy of the
variable to each object of a class.

class stdemo

static int num;

public void set()

num++;

public void get()

[Link]("Value : "+num);

class test

{
public static void main(String args[])

stdemo obj1=new stdemo();

stdemo obj2=new stdemo();

stdemo obj3=new stdemo();

[Link]();

[Link]();

[Link]();

[Link]();

[Link]();

[Link]();

______________________________________________________________________________
______

static methods-if you declare a method as static then you can call the particular method along
with the class name without creating the object.

class stdemo

public static void msg()

[Link]("Hi , i m Static Method");

}
class test

public static void main(String args[])

[Link]();

______________________________________________

static class - if a class contains the static members then it is known as static class.

method overriding- if we define a method is sub class which signature exactly mathched with
any other method of super class , then this term is known as method overriding.

class first

public void msg()

[Link]("This is Method of Super Class");

class sec extends first

{
public void msg()

[Link]();

[Link]("This is Method of Sub Class");

class test

public static void main(String args[])

sec obj=new sec();

[Link]();

______________________________

using final- we can use 3 variations of final keyword-

1. final variable

2. final method

3. final class

1. final variable- if you declare a variable as final then you can not change the value of that
variable during execution of the program. Means it will be a constant variable.

class test
{

public static void main(String args[])

final int a=10;

[Link](a);

//a=20;

//[Link](a);

______________________________

2. final method - if you define a method as final then you can not override the particular
method.

class first

final public void msg()

[Link]("This is Method of Super Class");

class sec extends first

public void msg()

[Link]();
[Link]("This is Method of Sub Class");

class test

public static void main(String args[])

sec obj=new sec();

[Link]();

_________________________

3. final Class- if you define a class as final means you can not inherit the particular class

final class first

public void msg()

[Link]("This is Method of Super Class");

class sec extends first

{
public void msg()

[Link]();

[Link]("This is Method of Sub Class");

class test

public static void main(String args[])

sec obj=new sec();

[Link]();

_______________________________________________________

interface & abstract class- They are used for desining the model of a system.

interface- it contains the list of unimplemented methods & defines the responsibility of a
class.

Syntax

interface interfacename

method prototype-1
method prototype-2

___________________

___________________

for implementing the interface on the class-

class classname implements interfacename

body of the class

Note - if you implements an interface in your class then you must override all the methods
whatever is declared inside the interface.

interface qamarwork

public boolean palindrome(int n);

public int reverse(int n);

class qamar implements qamarwork

public int reverse(int n)

int rev=0,r;

while(n>0)
{

r=n%10;

rev=rev*10+r;

n=n/10;

return rev;

public boolean palindrome(int n)

return n==reverse(n)?true:false;

class test

public static void main(String args[])

qamar obj=new qamar();

if([Link](121))

[Link]("Number is Palindrome");

else

[Link]("Number is Not Palindrome");

}
}

__________________________________________

abstract class- it same like interface but difference is that it contains implemented &
unimplemented methods both. and methods which will be unimplemented must define
asbtract methods. we inherit the abstract class but could not create the object of abstract
class.

abstract class qamarwork

abstract boolean palindrome(int n);

public int reverse(int n)

int rev=0,r;

while(n>0)

r=n%10;

rev=rev*10+r;

n=n/10;

return rev;

class qamar extends qamarwork

{
public boolean palindrome(int n)

return n==reverse(n)?true:false;

class test

public static void main(String args[])

qamar obj=new qamar();

if([Link](121))

[Link]("Number is Palindrome");

else

[Link]("Number is Not Palindrome");

Difference between abstract class and interface


Abstract class and interface both are used to achieve abstraction where we can declare
the abstract methods. Abstract class and interface both can't be instantiated.

But there are many differences between abstract class and interface that are given
below.
Abstract class Interface

1) Abstract class can have abstract and non- Interface can have only
abstract methods. abstract methods. Since Java 8, it can
have default and static methods also.

2) Abstract class doesn't support multiple Interface supports multiple


inheritance. inheritance.

3) Abstract class can have final, non-final, Interface has only static and final
static and non-static variables. variables.

4) Abstract class can provide the Interface can't provide the


implementation of interface. implementation of abstract class.

5) The abstract keyword is used to declare The interface keyword is used to


abstract class. declare interface.

6) An abstract class can extend another Java An interface can extend another Java
class and implement multiple Java interfaces. interface only.

7) An abstract class can be extended using An interface can be implemented using


keyword "extends". keyword "implements".

8) A Java abstract class can have class Members of a Java interface are public
members like private, protected, etc. by default.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves
fully abstraction (100%).

_______________________________________________________________
packages- It is like a folder which contains classes, and we can import them whenever is
required.

Steps for creating your own package.

1. create a folder in your system with the same name which you want for your package. for
eg opr

2. now open notepad & write program for package.

package opr;

public class qamar

public int reverse(int n)

int rev=0,r;

while(n>0)

r=n%10;

rev=rev*10+r;

n=n/10;

return rev;

public boolean palindrome(int n)

return n==reverse(n)?true:false;

}
}

3. svae your package inside the package folder.

4. now compile your package

5. now write a program for using the package

import opr.*;

class test

public static void main(String args[])

qamar obj=new qamar();

if([Link](121))

[Link]("Number is Palindrome");

else

[Link]("Number is Not Palindrome");

6. Save your program. like c:\

7. now set path again, like the following-

set path=java_path;package_folder_path

8. now run your program

__________________________________________________________

Exception Handling-
In a program there may be 3 types of errors could be generated these are-

1. Compile time errors

2. Logical Errors

3. Run Time Errors

Compile time errors are traced by the compiler and without debuging this your
program could not execute.

Logical erros are occured due to invalid logic of the programmer and this could be
traced by a programmer.

Run Time Errors- they are known as execeptions and when they occured they terminated the
execution a program.

The exception handling is a techniqe which allows you form handling run time exceptions.

java provides a block named as try.. catch.. block which is used for handling any exeception.

Syntax

try

java code....

}catch(ExceptionClassName objectName)

Message/Action

finally

Message/Action
}

note - finally is an optional block which execute in each case either exception is occured or
not?

import [Link].*;

class test

public static void main(String args[])

Scanner sc=new Scanner([Link]);

int a,b,c;

[Link]("Enter First Number :");

a=[Link]();

[Link]("Enter Second Number :");

b=[Link]();

try{

c=a/b;

[Link]("Result : "+c);

}catch(Exception e)

[Link]("Problem in Divide");

finally

[Link]("Bye..Bye");
}

[Link]("Some Other Work");

Built-in Exception Classes- java provides a lot of built in exception classes, which are used for
handling the exception as per the exception type.

Classes Meaning

IOException When I/O related problems occur

ArithmeticException When number is / by 0

ArrayIndexOutOfBoundsException When we want to access an array element which is not


exist in the array

StringIndexOutOfBoundsException When we want to access a string element which is not


exist in the string

ClassNotFoundException When the used class is not found

NullPointerException if an object is used without initilizing

using single try with multiple catch- if you want to handle the exception according to their
exception type then you can use single try with multiple catch-

class exec

public static void main(String args[])

int i;

for(i=1;i<=3;i++)
{

try{

switch(i)

case 1:

int a=10,b=0;

[Link](a/b);

break;

case 2:

String s="Bzar";

[Link]([Link](10));

break;

case 3:

int arr[]=new int[30];

[Link](arr[80]);

break;

}catch(ArrayIndexOutOfBoundsException ae)

[Link]("Array Related problem");

catch(StringIndexOutOfBoundsException se)

[Link]("String Related problem");


}

catch(ArithmeticException e)

[Link]("Number is / By 0");

________________________________________________________________________

using throws & throw statement-

throws - if you are not intrested to handle the run time exceptions then you can use throws
statement

import [Link].*;

class demo

public static void main(String args[]) throws IOException

InputStreamReader in=new InputStreamReader([Link]);

BufferedReader br=new BufferedReader(in);

int a,b,c;

[Link]("Enter First Number :");

a=[Link]([Link]());

[Link]("Enter Second Number :");

b=[Link]([Link]());
c=a+b;

[Link]("Sum : "+c);

throw- it is used for throwing our own exception.

import [Link].*;

class ownexec

public void inrange(int n) throws Exception

if(n>=1 && n<=10)

[Link](n+" is a valid Value");

else

throw new Exception(n+" is not a valid Value");

class test

public static void main(String args[])

Scanner sc=new Scanner([Link]);

int num;
[Link]("Enter Number :");

num=[Link]();

try{

ownexec obj=new ownexec();

[Link](num);

}catch(Exception e)

[Link]("Error : "+[Link]());

_______________________________________________

Common questions

Powered by AI

The 'this' keyword in Java refers to the current class instance variables and is used for differentiating instance variables from method parameters or other variables with the same name. The 'this()' method is used for constructor chaining within the same class. Conversely, the 'super' keyword refers to the parent class instance and is used to access parent class methods and variables. The 'super()' method is employed to call a parent class's constructor. These keywords facilitate clarity in specifying context within inheritance and method overloading .

Abstract classes can include both abstract and concrete methods, allowing partial implementation, whereas interfaces can only contain abstract methods until Java 8, which introduced default and static methods. Abstract classes can have both static and non-static variables, while interfaces can only have static final variables. Abstract classes do not support multiple inheritance, but interfaces do. This affects usage by imposing that abstract classes are used when similar classes share common state and behavior, whereas interfaces are used to define capabilities that can be added to different classes .

Exception handling in Java improves program reliability by allowing programs to respond gracefully to unforeseen runtime errors. This includes the use of try-catch blocks to encapsulate code that may throw exceptions and specifies actions to handle specific exceptions using catch clauses. The finally block provides a mechanism for executing code regardless of whether an exception occurs, typically for cleanup purposes. This structured approach prevents program crashes and maintains flow control, as illustrated by examples where different exception types are caught and messages are displayed accordingly .

Inheritance contributes to code reusability by allowing a subclass to use methods and fields of a superclass, which reduces code duplication and enforces a hierarchical relationship. However, only public members of a superclass are inherited by a subclass. For instance, in the provided source, the subclass 'sec' extends the superclass 'first', allowing it to access the public method 'one()' but not the private method 'privateone()' .

Method overloading is a form of polymorphism where a class can have multiple methods with the same name but different parameters. It allows methods to perform different tasks based on the parameter types or numbers passed to them. In the given sources, method overloading is implemented with methods like reverse() and lcm() that handle different data inputs—such as reversing digits of a number or characters of a string, and calculating the least common multiple for two to four integers, respectively .

In Java, the 'throws' keyword is used in a method signature to declare that a method can throw certain exceptions, thereby shifting responsibility to the method caller to handle these exceptions. The 'throw' statement, on the other hand, is used inside a method to throw an exception explicitly, often to indicate a specific error condition deliberately. In the examples, 'throws IOException' is utilized to indicate potential I/O exceptions without handling them directly, while the 'throw' statement is used to create a custom exception in the inrange() method to handle input validation .

Static variables in Java are shared across all instances of a class because they belong to the class itself, not any specific object. This makes them efficient for memory management when a variable is to be shared by multiple objects. Static methods, defined using the 'static' keyword, can be called without creating an instance of the class, making them utility methods, such as those that perform operations that do not require instance data. For instance, in the sources, the stdemo class demonstrates shared incrementing of a static variable 'num', and the static method 'msg()' can be called directly using the class name stdemo .

Creating user-defined packages in Java involves organizing classes into named folders, which aids in namespace management and code organization. The benefits include avoiding naming conflicts, better modularization of the codebase, and controlled access to classes and interfaces. The steps for creating such packages involve creating a directory named after the package, writing and saving the Java file within it, and ensuring proper package declaration in the source code. This organization facilitates the import and use of classes across projects, as shown by the usage of the 'opr' package example in the sources .

Method overriding is a core concept of polymorphism that allows a subclass to provide a specific implementation of a method already defined in its superclass. This enables dynamic method dispatch, where the call to an overridden method is resolved at runtime allowing for more flexible and extensible code. It supports the principle of 'programming to an interface' rather than an implementation. In the sources, class 'sec' extends 'first' and overrides the msg() method to provide a specific implementation that builds upon the superclass's method, enriching the object's behavior based on its type .

Constructors in Java are special methods invoked when an object is instantiated. Default constructors do not accept arguments and provide a simple way to initialize object fields. Parameterized constructors allow initial values to be passed to object fields during creation, offering flexibility in object state initialization. Overloaded constructors provide multiple ways to initialize objects based on different parameter inputs. The implications include improved control over object data during instantiation and enhanced code readability and flexibility. The examples illustrate these constructors: a default constructor initializes fields without arguments, parameterized constructors take initial values, and overloaded constructors enable different instantiation modes .

You might also like