How to use Categories class of org.junit.experimental.categories package

Best junit code snippet using org.junit.experimental.categories.Categories

Run junit automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1public class org.junit.experimental.categories.Categories$CategoryFilter extends org.junit.runner.manipulation.Filter {
2  public static org.junit.experimental.categories.Categories$CategoryFilter include(boolean, java.lang.Class<?>...);
3  public static org.junit.experimental.categories.Categories$CategoryFilter include(java.lang.Class<?>);
4  public static org.junit.experimental.categories.Categories$CategoryFilter include(java.lang.Class<?>...);
5  public static org.junit.experimental.categories.Categories$CategoryFilter exclude(boolean, java.lang.Class<?>...);
6  public static org.junit.experimental.categories.Categories$CategoryFilter exclude(java.lang.Class<?>);
7  public static org.junit.experimental.categories.Categories$CategoryFilter exclude(java.lang.Class<?>...);
8  public static org.junit.experimental.categories.Categories$CategoryFilter categoryFilter(boolean, java.util.Set<java.lang.Class<?>>, boolean, java.util.Set<java.lang.Class<?>>);
9  public org.junit.experimental.categories.Categories$CategoryFilter(java.lang.Class<?>, java.lang.Class<?>);
10  protected org.junit.experimental.categories.Categories$CategoryFilter(boolean, java.util.Set<java.lang.Class<?>>, boolean, java.util.Set<java.lang.Class<?>>);
11  public java.lang.String describe();
12  public java.lang.String toString();
13  public boolean shouldRun(org.junit.runner.Description);
14}
15
Full Screen
copy
1/*
2 * This Source Code Form is copyright of 51Degrees Mobile Experts Limited.
3 * Copyright © 2017 51Degrees Mobile Experts Limited, 5 Charlotte Close,
4 * Caversham, Reading, Berkshire, United Kingdom RG4 7BY
5 *
6 * This Source Code Form is the subject of the following patents and patent
7 * applications, owned by 51Degrees Mobile Experts Limited of 5 Charlotte
8 * Close, Caversham, Reading, Berkshire, United Kingdom RG4 7BY:
9 * European Patent No. 2871816;
10 * European Patent Application No. 17184134.9;
11 * United States Patent Nos. 9,332,086 and 9,350,823; and
12 * United States Patent Application No. 15/686,066.
13 *
14 * This Source Code Form is subject to the terms of the Mozilla Public
15 * License, v. 2.0.
16 *
17 * If a copy of the MPL was not distributed with this file, You can obtain
18 * one at http://mozilla.org/MPL/2.0/.
19 *
20 * This Source Code Form is "Incompatible With Secondary Licenses", as
21 * defined by the Mozilla Public License, v. 2.0.
22 */
23
24package fiftyone.mobile;
25
26/**
27 * Marker interfaces to identify different classes of tests. Allows skipping of tests
28 * where appropriate data set is not available, e.g. in downloaded open source
29 * where only the Lite data set is provided.
30 * <p>
31 * Note that when using these classes for configuration you must specify e.g. "TestType$DataSetEnterprise" as a reference
32 * to the inner class name
33 */
34public interface TestType {
35    /**
36     * Marker interface for tests that use the Enterprise data set for use with {@link org.junit.experimental.categories.Category}
37     */
38    interface DataSetEnterprise {}
39
40    /**
41     * Marker interface for tests that use the Lite data set  for use with {@link org.junit.experimental.categories.Category}
42     */
43    interface DataSetLite {}
44
45    /**
46     * Marker interface for tests that use the Premium data set for use with {@link org.junit.experimental.categories.Category}
47     */
48    interface DataSetPremium {}
49
50    /**
51     * Marker interface for tests that take a long time
52     */
53    interface Lengthy {}
54
55    /**
56     * Marker Interface for API Tests  for use with {@link org.junit.experimental.categories.Category}
57     */
58    interface TypeApi {}
59
60    /**
61     * Marker Interface for HTTP Header Tests for use with {@link org.junit.experimental.categories.Category}
62     */
63    interface TypeHttpHeader {}
64
65    /**
66     * Marker Interface for Memory Tests  for use with {@link org.junit.experimental.categories.Category}
67     */
68    interface TypeMemory {}
69
70    /**
71     * Marker Interface for Metadata Tests  for use with {@link org.junit.experimental.categories.Category}
72     */
73    interface TypeMetadata {}
74
75    /**
76     * Marker Interface for Performance Tests  for use with {@link org.junit.experimental.categories.Category}
77     */
78    interface TypePerformance {}
79    
80    /**
81     * Marker Interface for Unit Tests for use with {@link org.junit.experimental.categories.Category}
82     */
83    interface TypeUnit{}
84    
85    /**
86     * Marker Interface for Reconcile Tests for use with {@link org.junit.experimental.categories.Category}
87     */
88    interface TypeComparison{}
89}
90
Full Screen
copy
1package org.junit.experimental.categories;
2
3import java.util.HashSet;
4import java.util.List;
5import java.util.Set;
6
7import org.junit.experimental.categories.Categories.CategoryFilter;
8import org.junit.runner.manipulation.Filter;
9
10/**
11 * {@link org.junit.runner.FilterFactory} to exclude categories.
12 *
13 * The {@link Filter} that is created will filter out tests that are categorized with any of the
14 * given categories.
15 *
16 * Usage from command line:
17 * <code>
18 *     --filter=org.junit.experimental.categories.ExcludeCategories=pkg.of.Cat1,pkg.of.Cat2
19 * </code>
20 *
21 * Usage from API:
22 * <code>
23 *     new ExcludeCategories().createFilter(Cat1.class, Cat2.class);
24 * </code>
25 */
26public final class ExcludeCategories extends CategoryFilterFactory {
27    /**
28     * Creates a {@link Filter} which is only passed by tests that are
29     * not categorized with any of the specified categories.
30     *
31     * @param categories Category classes.
32     */
33    @Override
34    protected Filter createFilter(List<Class<?>> categories) {
35        return new ExcludesAny(categories);
36    }
37
38    private static class ExcludesAny extends CategoryFilter {
39        public ExcludesAny(List<Class<?>> categories) {
40            this(new HashSet<Class<?>>(categories));
41        }
42
43        public ExcludesAny(Set<Class<?>> categories) {
44            super(true, null, true, categories);
45        }
46
47        @Override
48        public String describe() {
49            return "excludes " + super.describe();
50        }
51    }
52}
53
Full Screen
copy
1    class Outter1 {
2
3        String OutStr;
4
5        Outter1(String str) {
6            OutStr = str;
7        }
8
9        public void NonStaticMethod(String st)  {
10
11            String temp1 = "ashish";
12            final String  tempFinal1 = "ashish"; 
13
14            //  below static attribute not permitted
15            // static String tempStatic1 = "static";    
16
17            //  below static with final attribute not permitted         
18            // static final String  tempStatic1 = "ashish";  
19
20            // synchronized keyword is not permitted below          
21            class localInnerNonStatic1 {            
22
23                synchronized    public void innerMethod(String str11) {
24                    str11 = temp1 +" sharma";
25                    System.out.println("innerMethod ===> "+str11);
26                }
27
28                /* 
29        //  static method with final not permitted
30          public static void innerStaticMethod(String str11) { 
31
32                    str11 = temp1 +" india";
33                    System.out.println("innerMethod ===> "+str11);
34                }*/
35            }
36
37            // static class not permitted below
38            //  static class localInnerStatic1 {   }                            
39
40        }
41
42        public static  void StaticMethod(String st)     {
43
44            String temp1 = "ashish";
45            final String  tempFinal1 = "ashish"; 
46
47            // static attribute not permitted below
48            //static String tempStatic1 = "static";     
49
50            //  static with final attribute not permitted below
51            // static final String  tempStatic1 = "ashish";                         
52
53            class localInnerNonStatic1 {
54                public void innerMethod(String str11) {
55                    str11 = temp1 +" sharma";
56                    System.out.println("innerMethod ===> "+str11);
57                }
58
59                /*
60    // static method with final not permitted
61    public static void innerStaticMethod(String str11) {  
62                    str11 = temp1 +" india";
63                    System.out.println("innerMethod ===> "+str11);
64                }*/
65            }
66
67            // static class not permitted below
68            //  static class localInnerStatic1 {   }    
69
70        }
71
72        // synchronized keyword is not permitted
73        static  class inner1 {          
74
75            static String  temp1 = "ashish";
76            String  tempNonStatic = "ashish";
77            // class localInner1 {
78
79            public void innerMethod(String str11) {
80                str11 = temp1 +" sharma";
81                str11 = str11+ tempNonStatic +" sharma";
82                System.out.println("innerMethod ===> "+str11);
83            }
84
85            public static void innerStaticMethod(String str11) {
86                //  error in below step
87                str11 = temp1 +" india";    
88                //str11 = str11+ tempNonStatic +" sharma";
89                System.out.println("innerMethod ===> "+str11);
90            }
91            //}
92        }
93
94        //synchronized keyword is not permitted below
95        class innerNonStatic1 {             
96
97//This is important we have to keep final with static modifier in non
98// static innerclass below
99            static final String  temp1 = "ashish";  
100            String  tempNonStatic = "ashish";
101            // class localInner1 {
102
103            synchronized    public void innerMethod(String str11) {
104                tempNonStatic = tempNonStatic +" ...";
105                str11 = temp1 +" sharma";
106                str11 = str11+ tempNonStatic +" sharma";
107                System.out.println("innerMethod ===> "+str11);
108            }
109
110            /*
111            //  error in below step
112            public static void innerStaticMethod(String str11) {   
113                            //  error in below step
114                            // str11 = tempNonStatic +" india";                     
115                            str11 = temp1 +" india";
116                            System.out.println("innerMethod ===> "+str11);
117                        }*/
118                    //}
119                }
120    }
121
Full Screen
copy
1public class Bank {
2
3    // maximum limit as per current bank policy
4    // is subject to change
5    private int maxLimit = 7000;
6
7    // ------- PUBLIC METHODS ---------
8
9    public CreditCard issueCard(
10            final String firstName,
11            final String lastName
12    ) {
13        final String number = this.generateNumber();
14        final int expiryDate = this.generateExpiryDate();
15        final int CVV = this.generateCVV();
16        return new CreditCard(firstName, lastName, number, expiryDate, CVV);
17    }
18
19
20    public boolean setLimit(
21            final CreditCard creditCard,
22            final int limit
23    ) {
24        if (limit <= this.maxLimit) {    // check against current bank policy limit
25            creditCard.setLimit(limit);  // access private method Bank.CreditCard.setLimit(int)
26            return true;
27        }
28        return false;
29    }
30
31    // ------- PRIVATE METHODS ---------
32
33    private String generateNumber() {
34        return "1234-5678-9101-1123";   // the numbers should be unique for each card
35    }
36
37
38    private int generateExpiryDate() {
39        return 202405;                  // date is YYYY=2024, MM=05
40    }
41
42
43    private int generateCVV() {
44        return 123;                     // is in real-life less predictable
45    }
46
47
48    // ------- PUBLIC STATIC NESTED CLASS ---------
49
50    public static final class CreditCard {
51        private final String firstName;
52        private final String lastName;
53        private final String number;
54        private final int expiryDate;
55        private final int CVV;
56
57        private int balance;
58        private int limit = 100; // default limit
59
60        // the constructor is final but is accessible from outer class
61        private CreditCard(
62                final String firstName,
63                final String lastName,
64                final String number,
65                final int expiryDate,
66                final int CVV
67        ) {
68            this.firstName = firstName;
69            this.lastName = lastName;
70            this.number = number;
71            this.expiryDate = expiryDate;
72            this.CVV = CVV;
73        }
74
75        // ------- PUBLIC METHODS ---------
76
77        public String getFirstName() {
78            return this.firstName;
79        }
80
81        public String getLastName() {
82            return this.lastName;
83        }
84
85        public String getNumber() {
86            return this.number;
87        }
88
89        public int getExpiryDate() {
90            return this.expiryDate;
91        }
92
93        // returns true if financial transaction is successful
94        // otherwise false
95        public boolean charge(final int amount) {
96            final int newBalance = this.balance - amount;
97            if (newBalance < -this.limit) {
98                return false;
99            }
100            this.balance = newBalance;
101            return true;
102        }
103
104        // ------- PRIVATE METHODS ---------
105
106        private int getCVV() {
107            return this.CVV;
108        }
109
110        private int getBalance() {
111            return this.balance;
112        }
113
114        private void setBalance(final int balance) {
115            this.balance = balance;
116        }
117
118        private int getLimit() {
119            return limit;
120        }
121
122        private void setLimit(final int limit) {
123            this.limit = limit;
124        }
125    }
126}
127
Full Screen
copy
1class OuterClass {
2...
3class NestedClass {
4    ...
5    }
6}
7
Full Screen
copy
1OuterClass.StaticNestedClass nestedObject =
2 new OuterClass.StaticNestedClass(); 
3
Full Screen
copy
1OuterClass.InnerClass innerObject = new OuterClass().new InnerClass();
2
Full Screen
copy
1OuterClass.InnerClass inner = new OuterClass().new InnerClass();
2
Full Screen
copy
1OuterClass.InnerClass inner = new OuterClass.InnerClass();
2
Full Screen
copy
1public class OuterClass {
2     private String someVariable = "Non Static";
3
4     private static String anotherStaticVariable = "Static";  
5
6     OuterClass(){
7
8     }
9
10     //Nested classes are static
11     static class StaticNestedClass{
12        private static String privateStaticNestedClassVariable = "Private Static Nested Class Variable"; 
13
14        //can access private variables declared in the outer class
15        public static void getPrivateVariableofOuterClass(){
16            System.out.println(anotherStaticVariable);
17        }
18     }
19
20     //non static
21     class InnerClass{
22
23         //can access private variables of outer class
24         public String getPrivateNonStaticVariableOfOuterClass(){
25             return someVariable;
26         }
27     }
28
29     public static void accessStaticClass(){
30         //can access any variable declared inside the Static Nested Class 
31         //even if it private
32         String var = OuterClass.StaticNestedClass.privateStaticNestedClassVariable; 
33         System.out.println(var);
34     }
35
36}
37
Full Screen
copy
1public class OuterClassTest {
2    public static void main(String[] args) {
3
4        //access the Static Nested Class
5        OuterClass.StaticNestedClass.getPrivateVariableofOuterClass();
6
7        //test the private variable declared inside the static nested class
8        OuterClass.accessStaticClass();
9        /*
10         * Inner Class Test
11         * */
12
13        //Declaration
14
15        //first instantiate the outer class
16        OuterClass outerClass = new OuterClass();
17
18        //then instantiate the inner class
19        OuterClass.InnerClass innerClassExample =  outerClass. new InnerClass();
20
21        //test the non static private variable
22        System.out.println(innerClassExample.getPrivateNonStaticVariableOfOuterClass()); 
23
24    }
25
26}
27
Full Screen
copy
1class Test{
2    private static int x = 1;
3        static class A{
4        private static int y = 2;
5        public static int getZ(){
6            return B.z+x;
7        }
8    }
9    static class B{
10        private static int z = 3;
11        public static int getY(){
12            return A.y;
13        }
14    }
15}
16
17class TestDemo{
18     public static void main(String[] args){
19        Test t = new Test();
20        System.out.println(Test.A.getZ());
21        System.out.println(Test.B.getY());
22    }
23}
24
Full Screen
copy
1    class Test{
2        private int i = 10;
3        class A{
4            private int i =20;
5            void display(){
6            int i = 30;
7            System.out.println(i);
8            System.out.println(this.i);
9            System.out.println(Test.this.i);
10        }
11    }
12}
13
Full Screen
copy
1 public static class A {} //ERROR
2
3 public class A {
4     public class B {
5         public static class C {} //ERROR
6     }
7 }
8
9 public class A {
10     public static class B {} //COMPILE !!!
11
12 }
13
Full Screen
copy
1public class BankAccount {
2
3    private long accountNumber;
4    private String owner;
5    ...
6
7    public static class Builder {
8
9    private long accountNumber;
10    private String owner;
11    ...
12
13    static public Builder(long accountNumber) {
14        this.accountNumber = accountNumber;
15    }
16
17    public Builder withOwner(String owner){
18        this.owner = owner;
19        return this; 
20    }
21
22    ...
23    public BankAccount build(){
24            BankAccount account = new BankAccount(); 
25            account.accountNumber = this.accountNumber;
26            account.owner = this.owner;
27            ...
28            return account;
29        }
30    }
31}
32
33
Full Screen
copy
1public class MyClass extends Applet {
2    ...
3        someObject.addMouseListener(new MyAdapter());
4    ...
5    class MyAdapter extends MouseAdapter {
6        public void mouseClicked(MouseEvent e) {
7            ...// Event listener implementation goes here...
8            ...// change some outer class instance property depend on the event
9        }
10    }
11}
12
Full Screen
copy
1public class InnerClassTest {
2    public static void main(String args[]) {      
3        //creating local inner class inside method i.e. main() 
4        class Local {
5            public void name() {
6                System.out.println("Example of Local class in Java");
7
8            }
9        }      
10        //creating instance of local inner class
11        Local local = new Local();
12        local.name(); //calling method from local inner class
13
14        //Creating anonymous inner class in Java for implementing thread
15        Thread anonymous = new Thread(){
16            @Override
17            public void run(){
18                System.out.println("Anonymous class example in java");
19            }
20        };
21        anonymous.start();
22
23        //example of creating instance of inner class
24        InnerClassTest test = new InnerClassTest();
25        InnerClassTest.Inner inner = test.new Inner();
26        inner.name(); //calling method of inner class
27    }
28
29     //Creating Inner class in Java
30    private class Inner{
31        public void name(){
32            System.out.println("Inner class example in java");
33        }
34    }
35}
36
Full Screen
copy
1public class NestedStaticExample {
2    public static void main(String args[]){  
3        StaticNested nested = new StaticNested();
4        nested.name();
5    }  
6    //static nested class in java
7    private static class StaticNested{
8        public void name(){
9            System.out.println("static nested class example in java");
10        }
11    }
12}
13
Full Screen
copy
1class OuterClass  {
2/*  some code here...*/
3     class InnerClass  {  }
4/*  some code here...*/
5}
6
Full Screen
copy
1class EnclosingClass {
2  static class Nested {
3    void someMethod() { System.out.println("hello SO"); }
4  }
5}
6
Full Screen
copy
1class NonEnclosingClass {
2
3  public static void main(String[] args) {
4    /*instantiate the Nested class that is a static
5      member of the EnclosingClass class:
6    */
7
8    EnclosingClass.Nested n = new EnclosingClass.Nested(); 
9    n.someMethod();  //prints out "hello"
10  }
11}
12
Full Screen
copy
1class EnclosingClass {
2
3  static class Nested {
4    void anotherMethod() { System.out.println("hi again"); } 
5  }
6
7  public static void main(String[] args) {
8    //access enclosed class:
9
10    Nested n = new Nested(); 
11    n.anotherMethod();  //prints out "hi again"
12  }
13
14}
15
Full Screen
copy
1public class A {
2    public class B {
3    }
4}
5
Full Screen
copy
1public class A {
2}
3
4A anon = new A() { /* you could change behavior of A here */ };
5
Full Screen
copy
1public class Outer {
2
3
4    public  class Inner {
5
6    }
7
8
9    public Inner inner(){
10        return new Inner();
11    }
12
13    @Override
14    protected void finalize() throws Throwable {
15    // as you know finalize is called by the garbage collector due to destroying an object instance
16        System.out.println("I am destroyed !");
17    }
18}
19
20
21public static void main(String arg[]) {
22
23    Outer outer = new Outer();
24    Outer.Inner inner = outer.new Inner();
25
26    // out instance is no more used and should be garbage collected !!!
27    // However this will not happen as inner instance is still alive i.e used, not null !
28    // and outer will be kept in memory until inner is destroyed
29    outer = null;
30
31    //
32    // inner = null;
33
34    //kick out garbage collector
35    System.gc();
36
37}
38
Full Screen
copy
1class A
2{
3  class B
4  {
5    // static int x; not allowed here…..    
6  }
7  static class C
8  {
9    static int x; // allowed here
10  }
11}
12
13class Test
14{
15  public static void main(String… str)
16  {
17    A o=new A();
18    A.B obj1 =o.new B();//need of inclosing instance
19
20    A.C obj2 =new A.C();
21
22    // not need of reference of object of outer class….
23  }
24}
25
Full Screen
copy
1public class C0 {
2
3    static C0 instance = null;
4
5    // Uncomment the following line and a null pointer exception will be
6    // generated before anything gets printed.
7    //public static final String outerItem = instance.makeString(98.6);
8
9    public C0() {
10        instance = this;
11    }
12
13    public String makeString(int i) {
14        return ((new Integer(i)).toString());
15    }
16
17    public String makeString(double d) {
18        return ((new Double(d)).toString());
19    }
20
21    public static final class nested {
22        public static final String innerItem = instance.makeString(42);
23    }
24
25    static public void main(String[] argv) {
26        System.out.println("start");
27        // Comment out this line and a null pointer exception will be
28        // generated after "start" prints and before the following
29        // try/catch block even gets entered.
30        new C0();
31        try {
32            System.out.println("retrieve item: " + nested.innerItem);
33        }
34        catch (Exception e) {
35            System.out.println("failed to retrieve item: " + e.toString());
36        }
37        System.out.println("finish");
38    }
39}
40
Full Screen
copy
1public class Outer {
2    public class Inner {}
3
4    public static class Nested {}
5}
6
Full Screen
copy
1outerclass outerobject=new outerobject();
2outerclass.innerclass innerobjcet=outerobject.new innerclass(); 
3
Full Screen
copy
1class outerclass A {
2    static class nestedclass B {
3        static int x = 10;
4    }
5}
6
Full Screen
copy
1  outerclass.nestedclass.x;  i.e. System.out.prinltn( outerclass.nestedclass.x);
2
Full Screen
copy
1public class OuterClass {
2    public static class Inner1 {
3    }
4    public class Inner2 {
5    }
6}
7
Full Screen
copy
1OuterClass outer = new OuterClass();
2OuterClass.Inner2 inner = outer.new Inner2();
3
Full Screen
copy
1OuterClass.Inner2 inner = new OuterClass().new Inner2();
2
Full Screen
copy
1OuterClass.Inner1 nestedObject = new OuterClass.Inner1();
2
Full Screen
copy
1public class Container {
2    public class Item{
3        Object data;
4        public Container getContainer(){
5            return Container.this;
6        }
7        public Item(Object data) {
8            super();
9            this.data = data;
10        }
11
12    }
13
14    public static Item create(Object data){
15        // does not compile since no instance of Container is available
16        return new Item(data);
17    }
18    public Item createSubItem(Object data){
19        // compiles, since 'this' Container is available
20        return new Item(data);
21    }
22}
23
Full Screen
copy
1// class version 49.0 (49)
2// access flags 33
3public class Container$Item {
4
5  // compiled from: Container.java
6  // access flags 1
7  public INNERCLASS Container$Item Container Item
8
9  // access flags 0
10  Object data
11
12  // access flags 4112
13  final Container this$0
14
15  // access flags 1
16  public getContainer() : Container
17   L0
18    LINENUMBER 7 L0
19    ALOAD 0: this
20    GETFIELD Container$Item.this$0 : Container
21    ARETURN
22   L1
23    LOCALVARIABLE this Container$Item L0 L1 0
24    MAXSTACK = 1
25    MAXLOCALS = 1
26
27  // access flags 1
28  public <init>(Container,Object) : void
29   L0
30    LINENUMBER 12 L0
31    ALOAD 0: this
32    ALOAD 1
33    PUTFIELD Container$Item.this$0 : Container
34   L1
35    LINENUMBER 10 L1
36    ALOAD 0: this
37    INVOKESPECIAL Object.<init>() : void
38   L2
39    LINENUMBER 11 L2
40    ALOAD 0: this
41    ALOAD 2: data
42    PUTFIELD Container$Item.data : Object
43    RETURN
44   L3
45    LOCALVARIABLE this Container$Item L0 L3 0
46    LOCALVARIABLE data Object L0 L3 2
47    MAXSTACK = 2
48    MAXLOCALS = 3
49}
50
Full Screen
copy
1OuterClass.InnerClass innerObject = outerObject.new InnerClass();
2
Full Screen
copy
1new InnerClass(outerObject)
2
Full Screen
copy
1package pizza;
2
3public class Rhino {
4
5    ...
6
7    public static class Goat {
8        ...
9    }
10}
11
Full Screen
copy
1package pizza;
2
3public class Rhino {
4
5    public class Goat {
6        ...
7    }
8
9    private void jerry() {
10        Goat g = new Goat();
11    }
12}
13
Full Screen
copy
1Rhino rhino = new Rhino();
2Rhino.Goat goat = rhino.new Goat();
3
Full Screen
copy
1public class Rhino {
2
3    private String barry;
4
5    public class Goat {
6        public void colin() {
7            System.out.println(barry);
8        }
9    }
10}
11
Full Screen
copy
1new *ParentClassName*(*constructorArgs*) {*members*}
2
Full Screen
copy
1new *InterfaceName*() {*members*}
2
Full Screen
copy
1OuterClass.StaticNestedClass
2
Full Screen
copy
1OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
2
Full Screen
copy
1class OuterClass {
2    ...
3    class InnerClass {
4        ...
5    }
6}
7
Full Screen
copy
1OuterClass outerObject = new OuterClass()
2OuterClass.InnerClass innerObject = outerObject.new InnerClass();
3
Full Screen
copy
1class A {
2  int t() { return 1; }
3  static A a =  new A() { int t() { return 2; } };
4}
5
Full Screen
copy
1import org.junit.Assert
2import org.junit.Before
3import org.junit.BeforeClass
4import org.junit.Test
5
6class FeatureTest {
7    companion object {
8        private lateinit var heavyFeature: HeavyFeature
9        @BeforeClass
10        @JvmStatic
11        fun beforeHeavy() {
12            heavyFeature = HeavyFeature()
13        }
14    }
15
16    private lateinit var feature: Feature
17
18    @Before
19    fun before() {
20        feature = Feature()
21    }
22
23    @Test
24    fun testCool() {
25        Assert.assertTrue(heavyFeature.cool())
26        Assert.assertTrue(feature.cool())
27    }
28
29    @Test
30    fun testWow() {
31        Assert.assertTrue(heavyFeature.wow())
32        Assert.assertTrue(feature.wow())
33    }
34}
35
Full Screen
copy
1import org.junit.Assert
2import org.junit.Test
3
4 class FeatureTest {
5    companion object {
6        private val heavyFeature = HeavyFeature()
7    }
8
9    private val feature = Feature()
10
11    @Test
12    fun testCool() {
13        Assert.assertTrue(heavyFeature.cool())
14        Assert.assertTrue(feature.cool())
15    }
16
17    @Test
18    fun testWow() {
19        Assert.assertTrue(heavyFeature.wow())
20        Assert.assertTrue(feature.wow())
21    }
22}
23
Full Screen
copy
1public class SampleClass {
2    public String initializeData(){
3        return "Initialize";
4    }
5
6    public String processDate(){
7        return "Process";
8    }
9 }
10
Full Screen
copy
1public class SampleTest {
2
3    private SampleClass sampleClass;
4
5    @BeforeClass
6    public static void beforeClassFunction(){
7        System.out.println("Before Class");
8    }
9
10    @Before
11    public void beforeFunction(){
12        sampleClass=new SampleClass();
13        System.out.println("Before Function");
14    }
15
16    @After
17    public void afterFunction(){
18        System.out.println("After Function");
19    }
20
21    @AfterClass
22    public static void afterClassFunction(){
23        System.out.println("After Class");
24    }
25
26    @Test
27    public void initializeTest(){
28        Assert.assertEquals("Initailization check", "Initialize", sampleClass.initializeData() );
29    }
30
31    @Test
32    public void processTest(){
33        Assert.assertEquals("Process check", "Process", sampleClass.processDate() );
34    }
35
36}
37
Full Screen
copy
1Before Class
2Before Function
3After Function
4Before Function
5After Function
6After Class
7
Full Screen
copy
1@Before = @BeforeEach
2@BeforeClass = @BeforeAll
3@After = @AfterEach
4@AfterClass = @AfterAll
5
Full Screen
copy
1+-------------------------------------------------------------------------------------------------------+
2¦                                       Feature                            ¦   Junit 4    ¦   Junit 5   ¦
3¦--------------------------------------------------------------------------+--------------+-------------¦
4¦ Execute before all test methods of the class are executed.               ¦ @BeforeClass ¦ @BeforeAll  ¦
5¦ Used with static method.                                                 ¦              ¦             ¦
6¦ For example, This method could contain some initialization code          ¦              ¦             ¦
7¦-------------------------------------------------------------------------------------------------------¦
8¦ Execute after all test methods in the current class.                     ¦ @AfterClass  ¦ @AfterAll   ¦
9¦ Used with static method.                                                 ¦              ¦             ¦
10¦ For example, This method could contain some cleanup code.                ¦              ¦             ¦
11¦-------------------------------------------------------------------------------------------------------¦
12¦ Execute before each test method.                                         ¦ @Before      ¦ @BeforeEach ¦
13¦ Used with non-static method.                                             ¦              ¦             ¦
14¦ For example, to reinitialize some class attributes used by the methods.  ¦              ¦             ¦
15¦-------------------------------------------------------------------------------------------------------¦
16¦ Execute after each test method.                                          ¦ @After       ¦ @AfterEach  ¦
17¦ Used with non-static method.                                             ¦              ¦             ¦
18¦ For example, to roll back database modifications.                        ¦              ¦             ¦
19+-------------------------------------------------------------------------------------------------------+
20
Full Screen
copy
1    class Outter1 {
2
3        String OutStr;
4
5        Outter1(String str) {
6            OutStr = str;
7        }
8
9        public void NonStaticMethod(String st)  {
10
11            String temp1 = "ashish";
12            final String  tempFinal1 = "ashish"; 
13
14            //  below static attribute not permitted
15            // static String tempStatic1 = "static";    
16
17            //  below static with final attribute not permitted         
18            // static final String  tempStatic1 = "ashish";  
19
20            // synchronized keyword is not permitted below          
21            class localInnerNonStatic1 {            
22
23                synchronized    public void innerMethod(String str11) {
24                    str11 = temp1 +" sharma";
25                    System.out.println("innerMethod ===> "+str11);
26                }
27
28                /* 
29        //  static method with final not permitted
30          public static void innerStaticMethod(String str11) { 
31
32                    str11 = temp1 +" india";
33                    System.out.println("innerMethod ===> "+str11);
34                }*/
35            }
36
37            // static class not permitted below
38            //  static class localInnerStatic1 {   }                            
39
40        }
41
42        public static  void StaticMethod(String st)     {
43
44            String temp1 = "ashish";
45            final String  tempFinal1 = "ashish"; 
46
47            // static attribute not permitted below
48            //static String tempStatic1 = "static";     
49
50            //  static with final attribute not permitted below
51            // static final String  tempStatic1 = "ashish";                         
52
53            class localInnerNonStatic1 {
54                public void innerMethod(String str11) {
55                    str11 = temp1 +" sharma";
56                    System.out.println("innerMethod ===> "+str11);
57                }
58
59                /*
60    // static method with final not permitted
61    public static void innerStaticMethod(String str11) {  
62                    str11 = temp1 +" india";
63                    System.out.println("innerMethod ===> "+str11);
64                }*/
65            }
66
67            // static class not permitted below
68            //  static class localInnerStatic1 {   }    
69
70        }
71
72        // synchronized keyword is not permitted
73        static  class inner1 {          
74
75            static String  temp1 = "ashish";
76            String  tempNonStatic = "ashish";
77            // class localInner1 {
78
79            public void innerMethod(String str11) {
80                str11 = temp1 +" sharma";
81                str11 = str11+ tempNonStatic +" sharma";
82                System.out.println("innerMethod ===> "+str11);
83            }
84
85            public static void innerStaticMethod(String str11) {
86                //  error in below step
87                str11 = temp1 +" india";    
88                //str11 = str11+ tempNonStatic +" sharma";
89                System.out.println("innerMethod ===> "+str11);
90            }
91            //}
92        }
93
94        //synchronized keyword is not permitted below
95        class innerNonStatic1 {             
96
97//This is important we have to keep final with static modifier in non
98// static innerclass below
99            static final String  temp1 = "ashish";  
100            String  tempNonStatic = "ashish";
101            // class localInner1 {
102
103            synchronized    public void innerMethod(String str11) {
104                tempNonStatic = tempNonStatic +" ...";
105                str11 = temp1 +" sharma";
106                str11 = str11+ tempNonStatic +" sharma";
107                System.out.println("innerMethod ===> "+str11);
108            }
109
110            /*
111            //  error in below step
112            public static void innerStaticMethod(String str11) {   
113                            //  error in below step
114                            // str11 = tempNonStatic +" india";                     
115                            str11 = temp1 +" india";
116                            System.out.println("innerMethod ===> "+str11);
117                        }*/
118                    //}
119                }
120    }
121
Full Screen
copy
1public class Bank {
2
3    // maximum limit as per current bank policy
4    // is subject to change
5    private int maxLimit = 7000;
6
7    // ------- PUBLIC METHODS ---------
8
9    public CreditCard issueCard(
10            final String firstName,
11            final String lastName
12    ) {
13        final String number = this.generateNumber();
14        final int expiryDate = this.generateExpiryDate();
15        final int CVV = this.generateCVV();
16        return new CreditCard(firstName, lastName, number, expiryDate, CVV);
17    }
18
19
20    public boolean setLimit(
21            final CreditCard creditCard,
22            final int limit
23    ) {
24        if (limit <= this.maxLimit) {    // check against current bank policy limit
25            creditCard.setLimit(limit);  // access private method Bank.CreditCard.setLimit(int)
26            return true;
27        }
28        return false;
29    }
30
31    // ------- PRIVATE METHODS ---------
32
33    private String generateNumber() {
34        return "1234-5678-9101-1123";   // the numbers should be unique for each card
35    }
36
37
38    private int generateExpiryDate() {
39        return 202405;                  // date is YYYY=2024, MM=05
40    }
41
42
43    private int generateCVV() {
44        return 123;                     // is in real-life less predictable
45    }
46
47
48    // ------- PUBLIC STATIC NESTED CLASS ---------
49
50    public static final class CreditCard {
51        private final String firstName;
52        private final String lastName;
53        private final String number;
54        private final int expiryDate;
55        private final int CVV;
56
57        private int balance;
58        private int limit = 100; // default limit
59
60        // the constructor is final but is accessible from outer class
61        private CreditCard(
62                final String firstName,
63                final String lastName,
64                final String number,
65                final int expiryDate,
66                final int CVV
67        ) {
68            this.firstName = firstName;
69            this.lastName = lastName;
70            this.number = number;
71            this.expiryDate = expiryDate;
72            this.CVV = CVV;
73        }
74
75        // ------- PUBLIC METHODS ---------
76
77        public String getFirstName() {
78            return this.firstName;
79        }
80
81        public String getLastName() {
82            return this.lastName;
83        }
84
85        public String getNumber() {
86            return this.number;
87        }
88
89        public int getExpiryDate() {
90            return this.expiryDate;
91        }
92
93        // returns true if financial transaction is successful
94        // otherwise false
95        public boolean charge(final int amount) {
96            final int newBalance = this.balance - amount;
97            if (newBalance < -this.limit) {
98                return false;
99            }
100            this.balance = newBalance;
101            return true;
102        }
103
104        // ------- PRIVATE METHODS ---------
105
106        private int getCVV() {
107            return this.CVV;
108        }
109
110        private int getBalance() {
111            return this.balance;
112        }
113
114        private void setBalance(final int balance) {
115            this.balance = balance;
116        }
117
118        private int getLimit() {
119            return limit;
120        }
121
122        private void setLimit(final int limit) {
123            this.limit = limit;
124        }
125    }
126}
127
Full Screen
copy
1class OuterClass {
2...
3class NestedClass {
4    ...
5    }
6}
7
Full Screen
copy
1OuterClass.StaticNestedClass nestedObject =
2 new OuterClass.StaticNestedClass(); 
3
Full Screen
copy
1OuterClass.InnerClass innerObject = new OuterClass().new InnerClass();
2
Full Screen
copy
1OuterClass.InnerClass inner = new OuterClass().new InnerClass();
2
Full Screen
copy
1OuterClass.InnerClass inner = new OuterClass.InnerClass();
2
Full Screen
copy
1public class OuterClass {
2     private String someVariable = "Non Static";
3
4     private static String anotherStaticVariable = "Static";  
5
6     OuterClass(){
7
8     }
9
10     //Nested classes are static
11     static class StaticNestedClass{
12        private static String privateStaticNestedClassVariable = "Private Static Nested Class Variable"; 
13
14        //can access private variables declared in the outer class
15        public static void getPrivateVariableofOuterClass(){
16            System.out.println(anotherStaticVariable);
17        }
18     }
19
20     //non static
21     class InnerClass{
22
23         //can access private variables of outer class
24         public String getPrivateNonStaticVariableOfOuterClass(){
25             return someVariable;
26         }
27     }
28
29     public static void accessStaticClass(){
30         //can access any variable declared inside the Static Nested Class 
31         //even if it private
32         String var = OuterClass.StaticNestedClass.privateStaticNestedClassVariable; 
33         System.out.println(var);
34     }
35
36}
37
Full Screen
copy
1public class OuterClassTest {
2    public static void main(String[] args) {
3
4        //access the Static Nested Class
5        OuterClass.StaticNestedClass.getPrivateVariableofOuterClass();
6
7        //test the private variable declared inside the static nested class
8        OuterClass.accessStaticClass();
9        /*
10         * Inner Class Test
11         * */
12
13        //Declaration
14
15        //first instantiate the outer class
16        OuterClass outerClass = new OuterClass();
17
18        //then instantiate the inner class
19        OuterClass.InnerClass innerClassExample =  outerClass. new InnerClass();
20
21        //test the non static private variable
22        System.out.println(innerClassExample.getPrivateNonStaticVariableOfOuterClass()); 
23
24    }
25
26}
27
Full Screen
copy
1class Test{
2    private static int x = 1;
3        static class A{
4        private static int y = 2;
5        public static int getZ(){
6            return B.z+x;
7        }
8    }
9    static class B{
10        private static int z = 3;
11        public static int getY(){
12            return A.y;
13        }
14    }
15}
16
17class TestDemo{
18     public static void main(String[] args){
19        Test t = new Test();
20        System.out.println(Test.A.getZ());
21        System.out.println(Test.B.getY());
22    }
23}
24
Full Screen
copy
1    class Test{
2        private int i = 10;
3        class A{
4            private int i =20;
5            void display(){
6            int i = 30;
7            System.out.println(i);
8            System.out.println(this.i);
9            System.out.println(Test.this.i);
10        }
11    }
12}
13
Full Screen
copy
1 public static class A {} //ERROR
2
3 public class A {
4     public class B {
5         public static class C {} //ERROR
6     }
7 }
8
9 public class A {
10     public static class B {} //COMPILE !!!
11
12 }
13
Full Screen
copy
1public class BankAccount {
2
3    private long accountNumber;
4    private String owner;
5    ...
6
7    public static class Builder {
8
9    private long accountNumber;
10    private String owner;
11    ...
12
13    static public Builder(long accountNumber) {
14        this.accountNumber = accountNumber;
15    }
16
17    public Builder withOwner(String owner){
18        this.owner = owner;
19        return this; 
20    }
21
22    ...
23    public BankAccount build(){
24            BankAccount account = new BankAccount(); 
25            account.accountNumber = this.accountNumber;
26            account.owner = this.owner;
27            ...
28            return account;
29        }
30    }
31}
32
33
Full Screen
copy
1public class MyClass extends Applet {
2    ...
3        someObject.addMouseListener(new MyAdapter());
4    ...
5    class MyAdapter extends MouseAdapter {
6        public void mouseClicked(MouseEvent e) {
7            ...// Event listener implementation goes here...
8            ...// change some outer class instance property depend on the event
9        }
10    }
11}
12
Full Screen
copy
1public class InnerClassTest {
2    public static void main(String args[]) {      
3        //creating local inner class inside method i.e. main() 
4        class Local {
5            public void name() {
6                System.out.println("Example of Local class in Java");
7
8            }
9        }      
10        //creating instance of local inner class
11        Local local = new Local();
12        local.name(); //calling method from local inner class
13
14        //Creating anonymous inner class in Java for implementing thread
15        Thread anonymous = new Thread(){
16            @Override
17            public void run(){
18                System.out.println("Anonymous class example in java");
19            }
20        };
21        anonymous.start();
22
23        //example of creating instance of inner class
24        InnerClassTest test = new InnerClassTest();
25        InnerClassTest.Inner inner = test.new Inner();
26        inner.name(); //calling method of inner class
27    }
28
29     //Creating Inner class in Java
30    private class Inner{
31        public void name(){
32            System.out.println("Inner class example in java");
33        }
34    }
35}
36
Full Screen
copy
1public class NestedStaticExample {
2    public static void main(String args[]){  
3        StaticNested nested = new StaticNested();
4        nested.name();
5    }  
6    //static nested class in java
7    private static class StaticNested{
8        public void name(){
9            System.out.println("static nested class example in java");
10        }
11    }
12}
13
Full Screen
copy
1class OuterClass  {
2/*  some code here...*/
3     class InnerClass  {  }
4/*  some code here...*/
5}
6
Full Screen
copy
1class EnclosingClass {
2  static class Nested {
3    void someMethod() { System.out.println("hello SO"); }
4  }
5}
6
Full Screen
copy
1class NonEnclosingClass {
2
3  public static void main(String[] args) {
4    /*instantiate the Nested class that is a static
5      member of the EnclosingClass class:
6    */
7
8    EnclosingClass.Nested n = new EnclosingClass.Nested(); 
9    n.someMethod();  //prints out "hello"
10  }
11}
12
Full Screen
copy
1class EnclosingClass {
2
3  static class Nested {
4    void anotherMethod() { System.out.println("hi again"); } 
5  }
6
7  public static void main(String[] args) {
8    //access enclosed class:
9
10    Nested n = new Nested(); 
11    n.anotherMethod();  //prints out "hi again"
12  }
13
14}
15
Full Screen
copy
1public class A {
2    public class B {
3    }
4}
5
Full Screen
copy
1public class A {
2}
3
4A anon = new A() { /* you could change behavior of A here */ };
5
Full Screen
copy
1public class Outer {
2
3
4    public  class Inner {
5
6    }
7
8
9    public Inner inner(){
10        return new Inner();
11    }
12
13    @Override
14    protected void finalize() throws Throwable {
15    // as you know finalize is called by the garbage collector due to destroying an object instance
16        System.out.println("I am destroyed !");
17    }
18}
19
20
21public static void main(String arg[]) {
22
23    Outer outer = new Outer();
24    Outer.Inner inner = outer.new Inner();
25
26    // out instance is no more used and should be garbage collected !!!
27    // However this will not happen as inner instance is still alive i.e used, not null !
28    // and outer will be kept in memory until inner is destroyed
29    outer = null;
30
31    //
32    // inner = null;
33
34    //kick out garbage collector
35    System.gc();
36
37}
38
Full Screen
copy
1class A
2{
3  class B
4  {
5    // static int x; not allowed here…..    
6  }
7  static class C
8  {
9    static int x; // allowed here
10  }
11}
12
13class Test
14{
15  public static void main(String… str)
16  {
17    A o=new A();
18    A.B obj1 =o.new B();//need of inclosing instance
19
20    A.C obj2 =new A.C();
21
22    // not need of reference of object of outer class….
23  }
24}
25
Full Screen
copy
1public class C0 {
2
3    static C0 instance = null;
4
5    // Uncomment the following line and a null pointer exception will be
6    // generated before anything gets printed.
7    //public static final String outerItem = instance.makeString(98.6);
8
9    public C0() {
10        instance = this;
11    }
12
13    public String makeString(int i) {
14        return ((new Integer(i)).toString());
15    }
16
17    public String makeString(double d) {
18        return ((new Double(d)).toString());
19    }
20
21    public static final class nested {
22        public static final String innerItem = instance.makeString(42);
23    }
24
25    static public void main(String[] argv) {
26        System.out.println("start");
27        // Comment out this line and a null pointer exception will be
28        // generated after "start" prints and before the following
29        // try/catch block even gets entered.
30        new C0();
31        try {
32            System.out.println("retrieve item: " + nested.innerItem);
33        }
34        catch (Exception e) {
35            System.out.println("failed to retrieve item: " + e.toString());
36        }
37        System.out.println("finish");
38    }
39}
40
Full Screen
copy
1public class Outer {
2    public class Inner {}
3
4    public static class Nested {}
5}
6
Full Screen
copy
1outerclass outerobject=new outerobject();
2outerclass.innerclass innerobjcet=outerobject.new innerclass(); 
3
Full Screen
copy
1class outerclass A {
2    static class nestedclass B {
3        static int x = 10;
4    }
5}
6
Full Screen
copy
1  outerclass.nestedclass.x;  i.e. System.out.prinltn( outerclass.nestedclass.x);
2
Full Screen
copy
1public class OuterClass {
2    public static class Inner1 {
3    }
4    public class Inner2 {
5    }
6}
7
Full Screen
copy
1OuterClass outer = new OuterClass();
2OuterClass.Inner2 inner = outer.new Inner2();
3
Full Screen
copy
1OuterClass.Inner2 inner = new OuterClass().new Inner2();
2
Full Screen
copy
1OuterClass.Inner1 nestedObject = new OuterClass.Inner1();
2
Full Screen
copy
1public class Container {
2    public class Item{
3        Object data;
4        public Container getContainer(){
5            return Container.this;
6        }
7        public Item(Object data) {
8            super();
9            this.data = data;
10        }
11
12    }
13
14    public static Item create(Object data){
15        // does not compile since no instance of Container is available
16        return new Item(data);
17    }
18    public Item createSubItem(Object data){
19        // compiles, since 'this' Container is available
20        return new Item(data);